blob: 3b181c85d261afff70c01891efa38f72b1c44ff9 [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
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic 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 Lattner173234a2008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000049#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000051#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000052#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000053#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000055#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000056#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000060#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000061#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000062#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000063using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000064using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000073 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000077 std::vector<Instruction*> Worklist;
78 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000079 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000080 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000082 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000083 InstCombiner() : FunctionPass((intptr_t)&ID) {}
84
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
88 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
89 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000109
Chris Lattnerdbab3862007-03-02 21:28:56 +0000110
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000115 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000118 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000119 }
120
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
125 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000127 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
139 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000141 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000142 // Set the operand to undef to drop the use.
143 I.setOperand(i, UndefValue::get(Op->getType()));
144 }
145
146 return R;
147 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000148
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000149 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000150 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000151
152 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153
Chris Lattner97e52e42002-04-28 21:27:06 +0000154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000155 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000156 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000157 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000158 }
159
Chris Lattner28977af2004-04-05 01:30:19 +0000160 TargetData &getTargetData() const { return *TD; }
161
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000166 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000168 //
Chris Lattner7e708292002-06-25 16:13:24 +0000169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
175 Instruction *commonRemTransforms(BinaryOperator &I);
176 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000177 Instruction *commonDivTransforms(BinaryOperator &I);
178 Instruction *commonIDivTransforms(BinaryOperator &I);
179 Instruction *visitUDiv(BinaryOperator &I);
180 Instruction *visitSDiv(BinaryOperator &I);
181 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000182 Instruction *visitAnd(BinaryOperator &I);
183 Instruction *visitOr (BinaryOperator &I);
184 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000185 Instruction *visitShl(BinaryOperator &I);
186 Instruction *visitAShr(BinaryOperator &I);
187 Instruction *visitLShr(BinaryOperator &I);
188 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000189 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
190 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000191 Instruction *visitFCmpInst(FCmpInst &I);
192 Instruction *visitICmpInst(ICmpInst &I);
193 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000194 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
195 Instruction *LHS,
196 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000197 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000199
Reid Spencere4d87aa2006-12-23 06:05:41 +0000200 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
201 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000202 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000203 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000204 Instruction *commonCastTransforms(CastInst &CI);
205 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000206 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000207 Instruction *visitTrunc(TruncInst &CI);
208 Instruction *visitZExt(ZExtInst &CI);
209 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000210 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000211 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000212 Instruction *visitFPToUI(FPToUIInst &FI);
213 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000214 Instruction *visitUIToFP(CastInst &CI);
215 Instruction *visitSIToFP(CastInst &CI);
216 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000217 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000218 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000219 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
220 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000221 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000222 Instruction *visitCallInst(CallInst &CI);
223 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000224 Instruction *visitPHINode(PHINode &PN);
225 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000226 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000227 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000228 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000229 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000230 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000231 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000232 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000233 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000234 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000235
236 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000237 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000238
Chris Lattner9fe38862003-06-19 17:00:31 +0000239 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000240 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000241 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000242 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000243 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
244 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000245 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000246
Chris Lattner28977af2004-04-05 01:30:19 +0000247 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000248 // InsertNewInstBefore - insert an instruction New before instruction Old
249 // in the program. Add the new instruction to the worklist.
250 //
Chris Lattner955f3312004-09-28 21:48:02 +0000251 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000252 assert(New && New->getParent() == 0 &&
253 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000254 BasicBlock *BB = Old.getParent();
255 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000256 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000257 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000258 }
259
Chris Lattner0c967662004-09-24 15:21:34 +0000260 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
261 /// This also adds the cast to the worklist. Finally, this returns the
262 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000263 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
264 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000265 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000266
Chris Lattnere2ed0572006-04-06 19:19:17 +0000267 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000268 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000269
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000270 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000271 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000272 return C;
273 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000274
275 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
276 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
277 }
278
Chris Lattner0c967662004-09-24 15:21:34 +0000279
Chris Lattner8b170942002-08-09 23:47:40 +0000280 // ReplaceInstUsesWith - This method is to be used when an instruction is
281 // found to be dead, replacable with another preexisting expression. Here
282 // we add all uses of I to the worklist, replace all uses of I with the new
283 // value, then return I, so that the inst combiner will know that I was
284 // modified.
285 //
286 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000287 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000288 if (&I != V) {
289 I.replaceAllUsesWith(V);
290 return &I;
291 } else {
292 // If we are replacing the instruction with itself, this must be in a
293 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000294 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000295 return &I;
296 }
Chris Lattner8b170942002-08-09 23:47:40 +0000297 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000298
Chris Lattner6dce1a72006-02-07 06:56:34 +0000299 // UpdateValueUsesWith - This method is to be used when an value is
300 // found to be replacable with another preexisting expression or was
301 // updated. Here we add all uses of I to the worklist, replace all uses of
302 // I with the new value (unless the instruction was just updated), then
303 // return true, so that the inst combiner will know that I was modified.
304 //
305 bool UpdateValueUsesWith(Value *Old, Value *New) {
306 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
307 if (Old != New)
308 Old->replaceAllUsesWith(New);
309 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000310 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000311 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000312 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000313 return true;
314 }
315
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000316 // EraseInstFromFunction - When dealing with an instruction that has side
317 // effects or produces a void value, we can't rely on DCE to delete the
318 // instruction. Instead, visit methods should return the value returned by
319 // this function.
320 Instruction *EraseInstFromFunction(Instruction &I) {
321 assert(I.use_empty() && "Cannot erase instruction that is used!");
322 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000323 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000324 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000325 return 0; // Don't do anything with FI
326 }
Chris Lattner173234a2008-06-02 01:18:21 +0000327
328 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329 APInt &KnownOne, unsigned Depth = 0) const {
330 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
331 }
332
333 bool MaskedValueIsZero(Value *V, const APInt &Mask,
334 unsigned Depth = 0) const {
335 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336 }
337 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338 return llvm::ComputeNumSignBits(Op, TD, Depth);
339 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000340
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000341 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000342 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
343 /// InsertBefore instruction. This is specialized a bit to avoid inserting
344 /// casts that are known to not do anything...
345 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000346 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
347 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000348 Instruction *InsertBefore);
349
Reid Spencere4d87aa2006-12-23 06:05:41 +0000350 /// SimplifyCommutative - This performs a few simplifications for
351 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000352 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000353
Reid Spencere4d87aa2006-12-23 06:05:41 +0000354 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
355 /// most-complex to least-complex order.
356 bool SimplifyCompare(CmpInst &I);
357
Reid Spencer2ec619a2007-03-23 21:24:59 +0000358 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
359 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000360 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
361 APInt& KnownZero, APInt& KnownOne,
362 unsigned Depth = 0);
363
Chris Lattner867b99f2006-10-05 06:55:50 +0000364 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
365 uint64_t &UndefElts, unsigned Depth = 0);
366
Chris Lattner4e998b22004-09-29 05:07:12 +0000367 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
368 // PHI node as operand #0, see if we can fold the instruction into the PHI
369 // (which is only possible if all operands to the PHI are constants).
370 Instruction *FoldOpIntoPhi(Instruction &I);
371
Chris Lattnerbac32862004-11-14 19:13:23 +0000372 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
373 // operator and they all are only used by the PHI, PHI together their
374 // inputs, and do the operation once, to the result of the PHI.
375 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000376 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
377
378
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000379 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
380 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000381
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000382 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000383 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000384 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000385 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000386 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000387 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000388 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000389 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000390 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000391
Chris Lattnerafe91a52006-06-15 19:07:26 +0000392
Reid Spencerc55b2432006-12-13 18:21:21 +0000393 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000394
Dan Gohmaneee962e2008-04-10 18:43:06 +0000395 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
396 unsigned CastOpc,
397 int &NumCastsRemoved);
398 unsigned GetOrEnforceKnownAlignment(Value *V,
399 unsigned PrefAlign = 0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000400 };
401}
402
Dan Gohman844731a2008-05-13 00:00:25 +0000403char InstCombiner::ID = 0;
404static RegisterPass<InstCombiner>
405X("instcombine", "Combine redundant instructions");
406
Chris Lattner4f98c562003-03-10 21:43:22 +0000407// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000408// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000409static unsigned getComplexity(Value *V) {
410 if (isa<Instruction>(V)) {
411 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000412 return 3;
413 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000414 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000415 if (isa<Argument>(V)) return 3;
416 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000417}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000418
Chris Lattnerc8802d22003-03-11 00:12:48 +0000419// isOnlyUse - Return true if this instruction will be deleted if we stop using
420// it.
421static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000422 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000423}
424
Chris Lattner4cb170c2004-02-23 06:38:22 +0000425// getPromotedType - Return the specified type promoted as it would be to pass
426// though a va_arg area...
427static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000428 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
429 if (ITy->getBitWidth() < 32)
430 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000431 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000432 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000433}
434
Reid Spencer3da59db2006-11-27 01:05:10 +0000435/// getBitCastOperand - If the specified operand is a CastInst or a constant
436/// expression bitcast, return the operand value, otherwise return null.
437static Value *getBitCastOperand(Value *V) {
438 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000439 return I->getOperand(0);
440 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000441 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000442 return CE->getOperand(0);
443 return 0;
444}
445
Reid Spencer3da59db2006-11-27 01:05:10 +0000446/// This function is a wrapper around CastInst::isEliminableCastPair. It
447/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000448static Instruction::CastOps
449isEliminableCastPair(
450 const CastInst *CI, ///< The first cast instruction
451 unsigned opcode, ///< The opcode of the second cast instruction
452 const Type *DstTy, ///< The target type for the second cast instruction
453 TargetData *TD ///< The target data for pointer size
454) {
455
456 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
457 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000458
Reid Spencer3da59db2006-11-27 01:05:10 +0000459 // Get the opcodes of the two Cast instructions
460 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
461 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000462
Reid Spencer3da59db2006-11-27 01:05:10 +0000463 return Instruction::CastOps(
464 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
465 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000466}
467
468/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
469/// in any code being generated. It does not require codegen if V is simple
470/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000471static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
472 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000473 if (V->getType() == Ty || isa<Constant>(V)) return false;
474
Chris Lattner01575b72006-05-25 23:24:33 +0000475 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000476 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000477 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000478 return false;
479 return true;
480}
481
482/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
483/// InsertBefore instruction. This is specialized a bit to avoid inserting
484/// casts that are known to not do anything...
485///
Reid Spencer17212df2006-12-12 09:18:51 +0000486Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
487 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000488 Instruction *InsertBefore) {
489 if (V->getType() == DestTy) return V;
490 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000491 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000492
Reid Spencer17212df2006-12-12 09:18:51 +0000493 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000494}
495
Chris Lattner4f98c562003-03-10 21:43:22 +0000496// SimplifyCommutative - This performs a few simplifications for commutative
497// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000498//
Chris Lattner4f98c562003-03-10 21:43:22 +0000499// 1. Order operands such that they are listed from right (least complex) to
500// left (most complex). This puts constants before unary operators before
501// binary operators.
502//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000503// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
504// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000505//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000506bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000507 bool Changed = false;
508 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
509 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000510
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 if (!I.isAssociative()) return Changed;
512 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000513 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
514 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
515 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000516 Constant *Folded = ConstantExpr::get(I.getOpcode(),
517 cast<Constant>(I.getOperand(1)),
518 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000519 I.setOperand(0, Op->getOperand(0));
520 I.setOperand(1, Folded);
521 return true;
522 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
523 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
524 isOnlyUse(Op) && isOnlyUse(Op1)) {
525 Constant *C1 = cast<Constant>(Op->getOperand(1));
526 Constant *C2 = cast<Constant>(Op1->getOperand(1));
527
528 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000529 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000530 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000531 Op1->getOperand(0),
532 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000533 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000534 I.setOperand(0, New);
535 I.setOperand(1, Folded);
536 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000537 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000538 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000539 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000540}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000541
Reid Spencere4d87aa2006-12-23 06:05:41 +0000542/// SimplifyCompare - For a CmpInst this function just orders the operands
543/// so that theyare listed from right (least complex) to left (most complex).
544/// This puts constants before unary operators before binary operators.
545bool InstCombiner::SimplifyCompare(CmpInst &I) {
546 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
547 return false;
548 I.swapOperands();
549 // Compare instructions are not associative so there's nothing else we can do.
550 return true;
551}
552
Chris Lattner8d969642003-03-10 23:06:50 +0000553// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
554// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000555//
Chris Lattner8d969642003-03-10 23:06:50 +0000556static inline Value *dyn_castNegVal(Value *V) {
557 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000558 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000559
Chris Lattner0ce85802004-12-14 20:08:06 +0000560 // Constants can be considered to be negated values if they can be folded.
561 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
562 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000563
564 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
565 if (C->getType()->getElementType()->isInteger())
566 return ConstantExpr::getNeg(C);
567
Chris Lattner8d969642003-03-10 23:06:50 +0000568 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000569}
570
Chris Lattner8d969642003-03-10 23:06:50 +0000571static inline Value *dyn_castNotVal(Value *V) {
572 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000573 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000574
575 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000576 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000577 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000578 return 0;
579}
580
Chris Lattnerc8802d22003-03-11 00:12:48 +0000581// dyn_castFoldableMul - If this value is a multiply that can be folded into
582// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000583// non-constant operand of the multiply, and set CST to point to the multiplier.
584// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000585//
Chris Lattner50af16a2004-11-13 19:50:12 +0000586static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000587 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000588 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000589 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000590 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000592 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000593 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000594 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000595 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000596 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000597 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000598 return I->getOperand(0);
599 }
600 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000601 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000602}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000603
Chris Lattner574da9b2005-01-13 20:14:25 +0000604/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
605/// expression, return it.
606static User *dyn_castGetElementPtr(Value *V) {
607 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
608 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
609 if (CE->getOpcode() == Instruction::GetElementPtr)
610 return cast<User>(V);
611 return false;
612}
613
Dan Gohmaneee962e2008-04-10 18:43:06 +0000614/// getOpcode - If this is an Instruction or a ConstantExpr, return the
615/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000616static unsigned getOpcode(const Value *V) {
617 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000618 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000619 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000620 return CE->getOpcode();
621 // Use UserOp1 to mean there's no opcode.
622 return Instruction::UserOp1;
623}
624
Reid Spencer7177c3a2007-03-25 05:33:51 +0000625/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000626static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000627 APInt Val(C->getValue());
628 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000629}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000630/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000631static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000632 APInt Val(C->getValue());
633 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000634}
635/// Add - Add two ConstantInts together
636static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
637 return ConstantInt::get(C1->getValue() + C2->getValue());
638}
639/// And - Bitwise AND two ConstantInts together
640static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
641 return ConstantInt::get(C1->getValue() & C2->getValue());
642}
643/// Subtract - Subtract one ConstantInt from another
644static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
645 return ConstantInt::get(C1->getValue() - C2->getValue());
646}
647/// Multiply - Multiply two ConstantInts together
648static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
649 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000650}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000651/// MultiplyOverflows - True if the multiply can not be expressed in an int
652/// this size.
653static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
654 uint32_t W = C1->getBitWidth();
655 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
656 if (sign) {
657 LHSExt.sext(W * 2);
658 RHSExt.sext(W * 2);
659 } else {
660 LHSExt.zext(W * 2);
661 RHSExt.zext(W * 2);
662 }
663
664 APInt MulExt = LHSExt * RHSExt;
665
666 if (sign) {
667 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
668 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
669 return MulExt.slt(Min) || MulExt.sgt(Max);
670 } else
671 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
672}
Chris Lattner955f3312004-09-28 21:48:02 +0000673
Reid Spencere7816b52007-03-08 01:52:58 +0000674
Chris Lattner255d8912006-02-11 09:31:47 +0000675/// ShrinkDemandedConstant - Check to see if the specified operand of the
676/// specified instruction is a constant integer. If so, check to see if there
677/// are any bits set in the constant that are not demanded. If so, shrink the
678/// constant and return true.
679static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000680 APInt Demanded) {
681 assert(I && "No instruction?");
682 assert(OpNo < I->getNumOperands() && "Operand index too large");
683
684 // If the operand is not a constant integer, nothing to do.
685 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
686 if (!OpC) return false;
687
688 // If there are no bits set that aren't demanded, nothing to do.
689 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
690 if ((~Demanded & OpC->getValue()) == 0)
691 return false;
692
693 // This instruction is producing bits that are not demanded. Shrink the RHS.
694 Demanded &= OpC->getValue();
695 I->setOperand(OpNo, ConstantInt::get(Demanded));
696 return true;
697}
698
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000699// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
700// set of known zero and one bits, compute the maximum and minimum values that
701// could have the specified known zero and known one bits, returning them in
702// min/max.
703static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000704 const APInt& KnownZero,
705 const APInt& KnownOne,
706 APInt& Min, APInt& Max) {
707 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
708 assert(KnownZero.getBitWidth() == BitWidth &&
709 KnownOne.getBitWidth() == BitWidth &&
710 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
711 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000712 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000713
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000714 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
715 // bit if it is unknown.
716 Min = KnownOne;
717 Max = KnownOne|UnknownBits;
718
Zhou Sheng4acf1552007-03-28 05:15:57 +0000719 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000720 Min.set(BitWidth-1);
721 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000722 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000723}
724
725// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
726// a set of known zero and one bits, compute the maximum and minimum values that
727// could have the specified known zero and known one bits, returning them in
728// min/max.
729static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000730 const APInt &KnownZero,
731 const APInt &KnownOne,
732 APInt &Min, APInt &Max) {
733 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000734 assert(KnownZero.getBitWidth() == BitWidth &&
735 KnownOne.getBitWidth() == BitWidth &&
736 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
737 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000738 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000739
740 // The minimum value is when the unknown bits are all zeros.
741 Min = KnownOne;
742 // The maximum value is when the unknown bits are all ones.
743 Max = KnownOne|UnknownBits;
744}
Chris Lattner255d8912006-02-11 09:31:47 +0000745
Reid Spencer8cb68342007-03-12 17:25:59 +0000746/// SimplifyDemandedBits - This function attempts to replace V with a simpler
747/// value based on the demanded bits. When this function is called, it is known
748/// that only the bits set in DemandedMask of the result of V are ever used
749/// downstream. Consequently, depending on the mask and V, it may be possible
750/// to replace V with a constant or one of its operands. In such cases, this
751/// function does the replacement and returns true. In all other cases, it
752/// returns false after analyzing the expression and setting KnownOne and known
753/// to be one in the expression. KnownZero contains all the bits that are known
754/// to be zero in the expression. These are provided to potentially allow the
755/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
756/// the expression. KnownOne and KnownZero always follow the invariant that
757/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
758/// the bits in KnownOne and KnownZero may only be accurate for those bits set
759/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
760/// and KnownOne must all be the same.
761bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
762 APInt& KnownZero, APInt& KnownOne,
763 unsigned Depth) {
764 assert(V != 0 && "Null pointer of Value???");
765 assert(Depth <= 6 && "Limit Search Depth");
766 uint32_t BitWidth = DemandedMask.getBitWidth();
767 const IntegerType *VTy = cast<IntegerType>(V->getType());
768 assert(VTy->getBitWidth() == BitWidth &&
769 KnownZero.getBitWidth() == BitWidth &&
770 KnownOne.getBitWidth() == BitWidth &&
771 "Value *V, DemandedMask, KnownZero and KnownOne \
772 must have same BitWidth");
773 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
774 // We know all of the bits for a constant!
775 KnownOne = CI->getValue() & DemandedMask;
776 KnownZero = ~KnownOne & DemandedMask;
777 return false;
778 }
779
Zhou Sheng96704452007-03-14 03:21:24 +0000780 KnownZero.clear();
781 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000782 if (!V->hasOneUse()) { // Other users may use these bits.
783 if (Depth != 0) { // Not at the root.
784 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
785 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
786 return false;
787 }
788 // If this is the root being simplified, allow it to have multiple uses,
789 // just set the DemandedMask to all bits.
790 DemandedMask = APInt::getAllOnesValue(BitWidth);
791 } else if (DemandedMask == 0) { // Not demanding any bits from V.
792 if (V != UndefValue::get(VTy))
793 return UpdateValueUsesWith(V, UndefValue::get(VTy));
794 return false;
795 } else if (Depth == 6) { // Limit search depth.
796 return false;
797 }
798
799 Instruction *I = dyn_cast<Instruction>(V);
800 if (!I) return false; // Only analyze instructions.
801
Reid Spencer8cb68342007-03-12 17:25:59 +0000802 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
803 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
804 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000805 default:
806 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
807 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000808 case Instruction::And:
809 // If either the LHS or the RHS are Zero, the result is zero.
810 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
811 RHSKnownZero, RHSKnownOne, Depth+1))
812 return true;
813 assert((RHSKnownZero & RHSKnownOne) == 0 &&
814 "Bits known to be one AND zero?");
815
816 // If something is known zero on the RHS, the bits aren't demanded on the
817 // LHS.
818 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
819 LHSKnownZero, LHSKnownOne, Depth+1))
820 return true;
821 assert((LHSKnownZero & LHSKnownOne) == 0 &&
822 "Bits known to be one AND zero?");
823
824 // If all of the demanded bits are known 1 on one side, return the other.
825 // These bits cannot contribute to the result of the 'and'.
826 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
827 (DemandedMask & ~LHSKnownZero))
828 return UpdateValueUsesWith(I, I->getOperand(0));
829 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
830 (DemandedMask & ~RHSKnownZero))
831 return UpdateValueUsesWith(I, I->getOperand(1));
832
833 // If all of the demanded bits in the inputs are known zeros, return zero.
834 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
835 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
836
837 // If the RHS is a constant, see if we can simplify it.
838 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
839 return UpdateValueUsesWith(I, I);
840
841 // Output known-1 bits are only known if set in both the LHS & RHS.
842 RHSKnownOne &= LHSKnownOne;
843 // Output known-0 are known to be clear if zero in either the LHS | RHS.
844 RHSKnownZero |= LHSKnownZero;
845 break;
846 case Instruction::Or:
847 // If either the LHS or the RHS are One, the result is One.
848 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
849 RHSKnownZero, RHSKnownOne, Depth+1))
850 return true;
851 assert((RHSKnownZero & RHSKnownOne) == 0 &&
852 "Bits known to be one AND zero?");
853 // If something is known one on the RHS, the bits aren't demanded on the
854 // LHS.
855 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
856 LHSKnownZero, LHSKnownOne, Depth+1))
857 return true;
858 assert((LHSKnownZero & LHSKnownOne) == 0 &&
859 "Bits known to be one AND zero?");
860
861 // If all of the demanded bits are known zero on one side, return the other.
862 // These bits cannot contribute to the result of the 'or'.
863 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
864 (DemandedMask & ~LHSKnownOne))
865 return UpdateValueUsesWith(I, I->getOperand(0));
866 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
867 (DemandedMask & ~RHSKnownOne))
868 return UpdateValueUsesWith(I, I->getOperand(1));
869
870 // If all of the potentially set bits on one side are known to be set on
871 // the other side, just use the 'other' side.
872 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
873 (DemandedMask & (~RHSKnownZero)))
874 return UpdateValueUsesWith(I, I->getOperand(0));
875 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
876 (DemandedMask & (~LHSKnownZero)))
877 return UpdateValueUsesWith(I, I->getOperand(1));
878
879 // If the RHS is a constant, see if we can simplify it.
880 if (ShrinkDemandedConstant(I, 1, DemandedMask))
881 return UpdateValueUsesWith(I, I);
882
883 // Output known-0 bits are only known if clear in both the LHS & RHS.
884 RHSKnownZero &= LHSKnownZero;
885 // Output known-1 are known to be set if set in either the LHS | RHS.
886 RHSKnownOne |= LHSKnownOne;
887 break;
888 case Instruction::Xor: {
889 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
890 RHSKnownZero, RHSKnownOne, Depth+1))
891 return true;
892 assert((RHSKnownZero & RHSKnownOne) == 0 &&
893 "Bits known to be one AND zero?");
894 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
895 LHSKnownZero, LHSKnownOne, Depth+1))
896 return true;
897 assert((LHSKnownZero & LHSKnownOne) == 0 &&
898 "Bits known to be one AND zero?");
899
900 // If all of the demanded bits are known zero on one side, return the other.
901 // These bits cannot contribute to the result of the 'xor'.
902 if ((DemandedMask & RHSKnownZero) == DemandedMask)
903 return UpdateValueUsesWith(I, I->getOperand(0));
904 if ((DemandedMask & LHSKnownZero) == DemandedMask)
905 return UpdateValueUsesWith(I, I->getOperand(1));
906
907 // Output known-0 bits are known if clear or set in both the LHS & RHS.
908 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
909 (RHSKnownOne & LHSKnownOne);
910 // Output known-1 are known to be set if set in only one of the LHS, RHS.
911 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
912 (RHSKnownOne & LHSKnownZero);
913
914 // If all of the demanded bits are known to be zero on one side or the
915 // other, turn this into an *inclusive* or.
916 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
917 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
918 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000919 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +0000920 I->getName());
921 InsertNewInstBefore(Or, *I);
922 return UpdateValueUsesWith(I, Or);
923 }
924
925 // If all of the demanded bits on one side are known, and all of the set
926 // bits on that side are also known to be set on the other side, turn this
927 // into an AND, as we know the bits will be cleared.
928 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
929 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
930 // all known
931 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
932 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
933 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000934 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +0000935 InsertNewInstBefore(And, *I);
936 return UpdateValueUsesWith(I, And);
937 }
938 }
939
940 // If the RHS is a constant, see if we can simplify it.
941 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
942 if (ShrinkDemandedConstant(I, 1, DemandedMask))
943 return UpdateValueUsesWith(I, I);
944
945 RHSKnownZero = KnownZeroOut;
946 RHSKnownOne = KnownOneOut;
947 break;
948 }
949 case Instruction::Select:
950 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
951 RHSKnownZero, RHSKnownOne, Depth+1))
952 return true;
953 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
954 LHSKnownZero, LHSKnownOne, Depth+1))
955 return true;
956 assert((RHSKnownZero & RHSKnownOne) == 0 &&
957 "Bits known to be one AND zero?");
958 assert((LHSKnownZero & LHSKnownOne) == 0 &&
959 "Bits known to be one AND zero?");
960
961 // If the operands are constants, see if we can simplify them.
962 if (ShrinkDemandedConstant(I, 1, DemandedMask))
963 return UpdateValueUsesWith(I, I);
964 if (ShrinkDemandedConstant(I, 2, DemandedMask))
965 return UpdateValueUsesWith(I, I);
966
967 // Only known if known in both the LHS and RHS.
968 RHSKnownOne &= LHSKnownOne;
969 RHSKnownZero &= LHSKnownZero;
970 break;
971 case Instruction::Trunc: {
972 uint32_t truncBf =
973 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +0000974 DemandedMask.zext(truncBf);
975 RHSKnownZero.zext(truncBf);
976 RHSKnownOne.zext(truncBf);
977 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
978 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +0000979 return true;
980 DemandedMask.trunc(BitWidth);
981 RHSKnownZero.trunc(BitWidth);
982 RHSKnownOne.trunc(BitWidth);
983 assert((RHSKnownZero & RHSKnownOne) == 0 &&
984 "Bits known to be one AND zero?");
985 break;
986 }
987 case Instruction::BitCast:
988 if (!I->getOperand(0)->getType()->isInteger())
989 return false;
990
991 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
992 RHSKnownZero, RHSKnownOne, Depth+1))
993 return true;
994 assert((RHSKnownZero & RHSKnownOne) == 0 &&
995 "Bits known to be one AND zero?");
996 break;
997 case Instruction::ZExt: {
998 // Compute the bits in the result that are not present in the input.
999 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001000 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001001
Zhou Shengd48653a2007-03-29 04:45:55 +00001002 DemandedMask.trunc(SrcBitWidth);
1003 RHSKnownZero.trunc(SrcBitWidth);
1004 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001005 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1006 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001007 return true;
1008 DemandedMask.zext(BitWidth);
1009 RHSKnownZero.zext(BitWidth);
1010 RHSKnownOne.zext(BitWidth);
1011 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1012 "Bits known to be one AND zero?");
1013 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001014 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001015 break;
1016 }
1017 case Instruction::SExt: {
1018 // Compute the bits in the result that are not present in the input.
1019 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001020 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001021
Reid Spencer8cb68342007-03-12 17:25:59 +00001022 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001023 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001024
Zhou Sheng01542f32007-03-29 02:26:30 +00001025 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001026 // If any of the sign extended bits are demanded, we know that the sign
1027 // bit is demanded.
1028 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001029 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001030
Zhou Shengd48653a2007-03-29 04:45:55 +00001031 InputDemandedBits.trunc(SrcBitWidth);
1032 RHSKnownZero.trunc(SrcBitWidth);
1033 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001034 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1035 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001036 return true;
1037 InputDemandedBits.zext(BitWidth);
1038 RHSKnownZero.zext(BitWidth);
1039 RHSKnownOne.zext(BitWidth);
1040 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1041 "Bits known to be one AND zero?");
1042
1043 // If the sign bit of the input is known set or clear, then we know the
1044 // top bits of the result.
1045
1046 // If the input sign bit is known zero, or if the NewBits are not demanded
1047 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001048 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001049 {
1050 // Convert to ZExt cast
1051 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1052 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001053 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001054 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001055 }
1056 break;
1057 }
1058 case Instruction::Add: {
1059 // Figure out what the input bits are. If the top bits of the and result
1060 // are not demanded, then the add doesn't demand them from its input
1061 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001062 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001063
1064 // If there is a constant on the RHS, there are a variety of xformations
1065 // we can do.
1066 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1067 // If null, this should be simplified elsewhere. Some of the xforms here
1068 // won't work if the RHS is zero.
1069 if (RHS->isZero())
1070 break;
1071
1072 // If the top bit of the output is demanded, demand everything from the
1073 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001074 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001075
1076 // Find information about known zero/one bits in the input.
1077 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1078 LHSKnownZero, LHSKnownOne, Depth+1))
1079 return true;
1080
1081 // If the RHS of the add has bits set that can't affect the input, reduce
1082 // the constant.
1083 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1084 return UpdateValueUsesWith(I, I);
1085
1086 // Avoid excess work.
1087 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1088 break;
1089
1090 // Turn it into OR if input bits are zero.
1091 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1092 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001093 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001094 I->getName());
1095 InsertNewInstBefore(Or, *I);
1096 return UpdateValueUsesWith(I, Or);
1097 }
1098
1099 // We can say something about the output known-zero and known-one bits,
1100 // depending on potential carries from the input constant and the
1101 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1102 // bits set and the RHS constant is 0x01001, then we know we have a known
1103 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1104
1105 // To compute this, we first compute the potential carry bits. These are
1106 // the bits which may be modified. I'm not aware of a better way to do
1107 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001108 const APInt& RHSVal = RHS->getValue();
1109 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001110
1111 // Now that we know which bits have carries, compute the known-1/0 sets.
1112
1113 // Bits are known one if they are known zero in one operand and one in the
1114 // other, and there is no input carry.
1115 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1116 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1117
1118 // Bits are known zero if they are known zero in both operands and there
1119 // is no input carry.
1120 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1121 } else {
1122 // If the high-bits of this ADD are not demanded, then it does not demand
1123 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001124 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001125 // Right fill the mask of bits for this ADD to demand the most
1126 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001127 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001128 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1129 LHSKnownZero, LHSKnownOne, Depth+1))
1130 return true;
1131 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1132 LHSKnownZero, LHSKnownOne, Depth+1))
1133 return true;
1134 }
1135 }
1136 break;
1137 }
1138 case Instruction::Sub:
1139 // If the high-bits of this SUB are not demanded, then it does not demand
1140 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001141 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001142 // Right fill the mask of bits for this SUB to demand the most
1143 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001144 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001146 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1147 LHSKnownZero, LHSKnownOne, Depth+1))
1148 return true;
1149 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1150 LHSKnownZero, LHSKnownOne, Depth+1))
1151 return true;
1152 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001153 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1154 // the known zeros and ones.
1155 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001156 break;
1157 case Instruction::Shl:
1158 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001159 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001160 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1161 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001162 RHSKnownZero, RHSKnownOne, Depth+1))
1163 return true;
1164 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1165 "Bits known to be one AND zero?");
1166 RHSKnownZero <<= ShiftAmt;
1167 RHSKnownOne <<= ShiftAmt;
1168 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001169 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001170 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001171 }
1172 break;
1173 case Instruction::LShr:
1174 // For a logical shift right
1175 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001176 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001177
Reid Spencer8cb68342007-03-12 17:25:59 +00001178 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001179 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1180 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001181 RHSKnownZero, RHSKnownOne, Depth+1))
1182 return true;
1183 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1184 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001185 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1186 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001187 if (ShiftAmt) {
1188 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001189 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001190 RHSKnownZero |= HighBits; // high bits known zero.
1191 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001192 }
1193 break;
1194 case Instruction::AShr:
1195 // If this is an arithmetic shift right and only the low-bit is set, we can
1196 // always convert this into a logical shr, even if the shift amount is
1197 // variable. The low bit of the shift cannot be an input sign bit unless
1198 // the shift amount is >= the size of the datatype, which is undefined.
1199 if (DemandedMask == 1) {
1200 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001201 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 I->getOperand(0), I->getOperand(1), I->getName());
1203 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1204 return UpdateValueUsesWith(I, NewVal);
1205 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001206
1207 // If the sign bit is the only bit demanded by this ashr, then there is no
1208 // need to do it, the shift doesn't change the high bit.
1209 if (DemandedMask.isSignBit())
1210 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001211
1212 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001213 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001214
Reid Spencer8cb68342007-03-12 17:25:59 +00001215 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001216 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001217 // If any of the "high bits" are demanded, we should set the sign bit as
1218 // demanded.
1219 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1220 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001221 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001222 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001223 RHSKnownZero, RHSKnownOne, Depth+1))
1224 return true;
1225 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1226 "Bits known to be one AND zero?");
1227 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001228 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001229 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1230 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1231
1232 // Handle the sign bits.
1233 APInt SignBit(APInt::getSignBit(BitWidth));
1234 // Adjust to where it is now in the mask.
1235 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1236
1237 // If the input sign bit is known to be zero, or if none of the top bits
1238 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001239 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001240 (HighBits & ~DemandedMask) == HighBits) {
1241 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001242 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 I->getOperand(0), SA, I->getName());
1244 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1245 return UpdateValueUsesWith(I, NewVal);
1246 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1247 RHSKnownOne |= HighBits;
1248 }
1249 }
1250 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001251 case Instruction::SRem:
1252 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1253 APInt RA = Rem->getValue();
1254 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001255 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001256 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1257 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1258 LHSKnownZero, LHSKnownOne, Depth+1))
1259 return true;
1260
1261 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1262 LHSKnownZero |= ~LowBits;
1263 else if (LHSKnownOne[BitWidth-1])
1264 LHSKnownOne |= ~LowBits;
1265
1266 KnownZero |= LHSKnownZero & DemandedMask;
1267 KnownOne |= LHSKnownOne & DemandedMask;
1268
1269 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1270 }
1271 }
1272 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001273 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001274 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1275 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001276 if (RA.isPowerOf2()) {
1277 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001278 APInt Mask2 = LowBits & DemandedMask;
1279 KnownZero |= ~LowBits & DemandedMask;
1280 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1281 KnownZero, KnownOne, Depth+1))
1282 return true;
1283
1284 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001285 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001286 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001287 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001288
1289 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1290 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001291 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1292 KnownZero2, KnownOne2, Depth+1))
1293 return true;
1294
Dan Gohman23e8b712008-04-28 17:02:21 +00001295 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001296 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001297 KnownZero2, KnownOne2, Depth+1))
1298 return true;
1299
1300 Leaders = std::max(Leaders,
1301 KnownZero2.countLeadingOnes());
1302 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001303 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001304 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001305 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001306
1307 // If the client is only demanding bits that we know, return the known
1308 // constant.
1309 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1310 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1311 return false;
1312}
1313
Chris Lattner867b99f2006-10-05 06:55:50 +00001314
1315/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1316/// 64 or fewer elements. DemandedElts contains the set of elements that are
1317/// actually used by the caller. This method analyzes which elements of the
1318/// operand are undef and returns that information in UndefElts.
1319///
1320/// If the information about demanded elements can be used to simplify the
1321/// operation, the operation is simplified, then the resultant value is
1322/// returned. This returns null if no change was made.
1323Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1324 uint64_t &UndefElts,
1325 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001326 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001327 assert(VWidth <= 64 && "Vector too wide to analyze!");
1328 uint64_t EltMask = ~0ULL >> (64-VWidth);
1329 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1330 "Invalid DemandedElts!");
1331
1332 if (isa<UndefValue>(V)) {
1333 // If the entire vector is undefined, just return this info.
1334 UndefElts = EltMask;
1335 return 0;
1336 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1337 UndefElts = EltMask;
1338 return UndefValue::get(V->getType());
1339 }
1340
1341 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001342 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1343 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001344 Constant *Undef = UndefValue::get(EltTy);
1345
1346 std::vector<Constant*> Elts;
1347 for (unsigned i = 0; i != VWidth; ++i)
1348 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1349 Elts.push_back(Undef);
1350 UndefElts |= (1ULL << i);
1351 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1352 Elts.push_back(Undef);
1353 UndefElts |= (1ULL << i);
1354 } else { // Otherwise, defined.
1355 Elts.push_back(CP->getOperand(i));
1356 }
1357
1358 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001359 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001360 return NewCP != CP ? NewCP : 0;
1361 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001362 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001363 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001364 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001365 Constant *Zero = Constant::getNullValue(EltTy);
1366 Constant *Undef = UndefValue::get(EltTy);
1367 std::vector<Constant*> Elts;
1368 for (unsigned i = 0; i != VWidth; ++i)
1369 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1370 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001371 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001372 }
1373
1374 if (!V->hasOneUse()) { // Other users may use these bits.
1375 if (Depth != 0) { // Not at the root.
1376 // TODO: Just compute the UndefElts information recursively.
1377 return false;
1378 }
1379 return false;
1380 } else if (Depth == 10) { // Limit search depth.
1381 return false;
1382 }
1383
1384 Instruction *I = dyn_cast<Instruction>(V);
1385 if (!I) return false; // Only analyze instructions.
1386
1387 bool MadeChange = false;
1388 uint64_t UndefElts2;
1389 Value *TmpV;
1390 switch (I->getOpcode()) {
1391 default: break;
1392
1393 case Instruction::InsertElement: {
1394 // If this is a variable index, we don't know which element it overwrites.
1395 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001396 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001397 if (Idx == 0) {
1398 // Note that we can't propagate undef elt info, because we don't know
1399 // which elt is getting updated.
1400 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1401 UndefElts2, Depth+1);
1402 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1403 break;
1404 }
1405
1406 // If this is inserting an element that isn't demanded, remove this
1407 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001408 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001409 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1410 return AddSoonDeadInstToWorklist(*I, 0);
1411
1412 // Otherwise, the element inserted overwrites whatever was there, so the
1413 // input demanded set is simpler than the output set.
1414 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1415 DemandedElts & ~(1ULL << IdxNo),
1416 UndefElts, Depth+1);
1417 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1418
1419 // The inserted element is defined.
1420 UndefElts |= 1ULL << IdxNo;
1421 break;
1422 }
Chris Lattner69878332007-04-14 22:29:23 +00001423 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001424 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001425 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1426 if (!VTy) break;
1427 unsigned InVWidth = VTy->getNumElements();
1428 uint64_t InputDemandedElts = 0;
1429 unsigned Ratio;
1430
1431 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001432 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001433 // elements as are demanded of us.
1434 Ratio = 1;
1435 InputDemandedElts = DemandedElts;
1436 } else if (VWidth > InVWidth) {
1437 // Untested so far.
1438 break;
1439
1440 // If there are more elements in the result than there are in the source,
1441 // then an input element is live if any of the corresponding output
1442 // elements are live.
1443 Ratio = VWidth/InVWidth;
1444 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1445 if (DemandedElts & (1ULL << OutIdx))
1446 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1447 }
1448 } else {
1449 // Untested so far.
1450 break;
1451
1452 // If there are more elements in the source than there are in the result,
1453 // then an input element is live if the corresponding output element is
1454 // live.
1455 Ratio = InVWidth/VWidth;
1456 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1457 if (DemandedElts & (1ULL << InIdx/Ratio))
1458 InputDemandedElts |= 1ULL << InIdx;
1459 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001460
Chris Lattner69878332007-04-14 22:29:23 +00001461 // div/rem demand all inputs, because they don't want divide by zero.
1462 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1463 UndefElts2, Depth+1);
1464 if (TmpV) {
1465 I->setOperand(0, TmpV);
1466 MadeChange = true;
1467 }
1468
1469 UndefElts = UndefElts2;
1470 if (VWidth > InVWidth) {
1471 assert(0 && "Unimp");
1472 // If there are more elements in the result than there are in the source,
1473 // then an output element is undef if the corresponding input element is
1474 // undef.
1475 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1476 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1477 UndefElts |= 1ULL << OutIdx;
1478 } else if (VWidth < InVWidth) {
1479 assert(0 && "Unimp");
1480 // If there are more elements in the source than there are in the result,
1481 // then a result element is undef if all of the corresponding input
1482 // elements are undef.
1483 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1484 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1485 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1486 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1487 }
1488 break;
1489 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001490 case Instruction::And:
1491 case Instruction::Or:
1492 case Instruction::Xor:
1493 case Instruction::Add:
1494 case Instruction::Sub:
1495 case Instruction::Mul:
1496 // div/rem demand all inputs, because they don't want divide by zero.
1497 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1498 UndefElts, Depth+1);
1499 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1500 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1501 UndefElts2, Depth+1);
1502 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1503
1504 // Output elements are undefined if both are undefined. Consider things
1505 // like undef&0. The result is known zero, not undef.
1506 UndefElts &= UndefElts2;
1507 break;
1508
1509 case Instruction::Call: {
1510 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1511 if (!II) break;
1512 switch (II->getIntrinsicID()) {
1513 default: break;
1514
1515 // Binary vector operations that work column-wise. A dest element is a
1516 // function of the corresponding input elements from the two inputs.
1517 case Intrinsic::x86_sse_sub_ss:
1518 case Intrinsic::x86_sse_mul_ss:
1519 case Intrinsic::x86_sse_min_ss:
1520 case Intrinsic::x86_sse_max_ss:
1521 case Intrinsic::x86_sse2_sub_sd:
1522 case Intrinsic::x86_sse2_mul_sd:
1523 case Intrinsic::x86_sse2_min_sd:
1524 case Intrinsic::x86_sse2_max_sd:
1525 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1526 UndefElts, Depth+1);
1527 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1528 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1529 UndefElts2, Depth+1);
1530 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1531
1532 // If only the low elt is demanded and this is a scalarizable intrinsic,
1533 // scalarize it now.
1534 if (DemandedElts == 1) {
1535 switch (II->getIntrinsicID()) {
1536 default: break;
1537 case Intrinsic::x86_sse_sub_ss:
1538 case Intrinsic::x86_sse_mul_ss:
1539 case Intrinsic::x86_sse2_sub_sd:
1540 case Intrinsic::x86_sse2_mul_sd:
1541 // TODO: Lower MIN/MAX/ABS/etc
1542 Value *LHS = II->getOperand(1);
1543 Value *RHS = II->getOperand(2);
1544 // Extract the element as scalars.
1545 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1546 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1547
1548 switch (II->getIntrinsicID()) {
1549 default: assert(0 && "Case stmts out of sync!");
1550 case Intrinsic::x86_sse_sub_ss:
1551 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001552 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001553 II->getName()), *II);
1554 break;
1555 case Intrinsic::x86_sse_mul_ss:
1556 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001557 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001558 II->getName()), *II);
1559 break;
1560 }
1561
1562 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001563 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1564 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001565 InsertNewInstBefore(New, *II);
1566 AddSoonDeadInstToWorklist(*II, 0);
1567 return New;
1568 }
1569 }
1570
1571 // Output elements are undefined if both are undefined. Consider things
1572 // like undef&0. The result is known zero, not undef.
1573 UndefElts &= UndefElts2;
1574 break;
1575 }
1576 break;
1577 }
1578 }
1579 return MadeChange ? I : 0;
1580}
1581
Dan Gohman45b4e482008-05-19 22:14:15 +00001582
Chris Lattner564a7272003-08-13 19:01:45 +00001583/// AssociativeOpt - Perform an optimization on an associative operator. This
1584/// function is designed to check a chain of associative operators for a
1585/// potential to apply a certain optimization. Since the optimization may be
1586/// applicable if the expression was reassociated, this checks the chain, then
1587/// reassociates the expression as necessary to expose the optimization
1588/// opportunity. This makes use of a special Functor, which must define
1589/// 'shouldApply' and 'apply' methods.
1590///
1591template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001592static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001593 unsigned Opcode = Root.getOpcode();
1594 Value *LHS = Root.getOperand(0);
1595
1596 // Quick check, see if the immediate LHS matches...
1597 if (F.shouldApply(LHS))
1598 return F.apply(Root);
1599
1600 // Otherwise, if the LHS is not of the same opcode as the root, return.
1601 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001602 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001603 // Should we apply this transform to the RHS?
1604 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1605
1606 // If not to the RHS, check to see if we should apply to the LHS...
1607 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1608 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1609 ShouldApply = true;
1610 }
1611
1612 // If the functor wants to apply the optimization to the RHS of LHSI,
1613 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1614 if (ShouldApply) {
1615 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001616
Chris Lattner564a7272003-08-13 19:01:45 +00001617 // Now all of the instructions are in the current basic block, go ahead
1618 // and perform the reassociation.
1619 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1620
1621 // First move the selected RHS to the LHS of the root...
1622 Root.setOperand(0, LHSI->getOperand(1));
1623
1624 // Make what used to be the LHS of the root be the user of the root...
1625 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001626 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001627 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1628 return 0;
1629 }
Chris Lattner65725312004-04-16 18:08:07 +00001630 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001631 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001632 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1633 BasicBlock::iterator ARI = &Root; ++ARI;
1634 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1635 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001636
1637 // Now propagate the ExtraOperand down the chain of instructions until we
1638 // get to LHSI.
1639 while (TmpLHSI != LHSI) {
1640 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001641 // Move the instruction to immediately before the chain we are
1642 // constructing to avoid breaking dominance properties.
1643 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1644 BB->getInstList().insert(ARI, NextLHSI);
1645 ARI = NextLHSI;
1646
Chris Lattner564a7272003-08-13 19:01:45 +00001647 Value *NextOp = NextLHSI->getOperand(1);
1648 NextLHSI->setOperand(1, ExtraOperand);
1649 TmpLHSI = NextLHSI;
1650 ExtraOperand = NextOp;
1651 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001652
Chris Lattner564a7272003-08-13 19:01:45 +00001653 // Now that the instructions are reassociated, have the functor perform
1654 // the transformation...
1655 return F.apply(Root);
1656 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001657
Chris Lattner564a7272003-08-13 19:01:45 +00001658 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1659 }
1660 return 0;
1661}
1662
Dan Gohman844731a2008-05-13 00:00:25 +00001663namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001664
Nick Lewycky02d639f2008-05-23 04:34:58 +00001665// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001666struct AddRHS {
1667 Value *RHS;
1668 AddRHS(Value *rhs) : RHS(rhs) {}
1669 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1670 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001671 return BinaryOperator::CreateShl(Add.getOperand(0),
1672 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001673 }
1674};
1675
1676// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1677// iff C1&C2 == 0
1678struct AddMaskingAnd {
1679 Constant *C2;
1680 AddMaskingAnd(Constant *c) : C2(c) {}
1681 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001682 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001683 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001684 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001685 }
1686 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001687 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001688 }
1689};
1690
Dan Gohman844731a2008-05-13 00:00:25 +00001691}
1692
Chris Lattner6e7ba452005-01-01 16:22:27 +00001693static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001694 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001695 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001696 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001697 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001698
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001699 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00001700 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001701 }
1702
Chris Lattner2eefe512004-04-09 19:05:30 +00001703 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001704 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1705 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001706
Chris Lattner2eefe512004-04-09 19:05:30 +00001707 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1708 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001709 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1710 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001711 }
1712
1713 Value *Op0 = SO, *Op1 = ConstOperand;
1714 if (!ConstIsRHS)
1715 std::swap(Op0, Op1);
1716 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001717 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001718 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001719 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001720 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001721 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001722 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001723 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001724 abort();
1725 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001726 return IC->InsertNewInstBefore(New, I);
1727}
1728
1729// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1730// constant as the other operand, try to fold the binary operator into the
1731// select arguments. This also works for Cast instructions, which obviously do
1732// not have a second operand.
1733static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1734 InstCombiner *IC) {
1735 // Don't modify shared select instructions
1736 if (!SI->hasOneUse()) return 0;
1737 Value *TV = SI->getOperand(1);
1738 Value *FV = SI->getOperand(2);
1739
1740 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001741 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001742 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001743
Chris Lattner6e7ba452005-01-01 16:22:27 +00001744 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1745 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1746
Gabor Greif051a9502008-04-06 20:25:17 +00001747 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1748 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001749 }
1750 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001751}
1752
Chris Lattner4e998b22004-09-29 05:07:12 +00001753
1754/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1755/// node as operand #0, see if we can fold the instruction into the PHI (which
1756/// is only possible if all operands to the PHI are constants).
1757Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1758 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001759 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001760 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001761
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001762 // Check to see if all of the operands of the PHI are constants. If there is
1763 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001764 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001765 BasicBlock *NonConstBB = 0;
1766 for (unsigned i = 0; i != NumPHIValues; ++i)
1767 if (!isa<Constant>(PN->getIncomingValue(i))) {
1768 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001769 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001770 NonConstBB = PN->getIncomingBlock(i);
1771
1772 // If the incoming non-constant value is in I's block, we have an infinite
1773 // loop.
1774 if (NonConstBB == I.getParent())
1775 return 0;
1776 }
1777
1778 // If there is exactly one non-constant value, we can insert a copy of the
1779 // operation in that block. However, if this is a critical edge, we would be
1780 // inserting the computation one some other paths (e.g. inside a loop). Only
1781 // do this if the pred block is unconditionally branching into the phi block.
1782 if (NonConstBB) {
1783 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1784 if (!BI || !BI->isUnconditional()) return 0;
1785 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001786
1787 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001788 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001789 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001790 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001791 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001792
1793 // Next, add all of the operands to the PHI.
1794 if (I.getNumOperands() == 2) {
1795 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001796 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001797 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001798 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001799 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1800 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1801 else
1802 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001803 } else {
1804 assert(PN->getIncomingBlock(i) == NonConstBB);
1805 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001806 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001807 PN->getIncomingValue(i), C, "phitmp",
1808 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001809 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001810 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001811 CI->getPredicate(),
1812 PN->getIncomingValue(i), C, "phitmp",
1813 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001814 else
1815 assert(0 && "Unknown binop!");
1816
Chris Lattnerdbab3862007-03-02 21:28:56 +00001817 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001818 }
1819 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001820 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001821 } else {
1822 CastInst *CI = cast<CastInst>(&I);
1823 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001824 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001825 Value *InV;
1826 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001827 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001828 } else {
1829 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001830 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001831 I.getType(), "phitmp",
1832 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001833 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001834 }
1835 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001836 }
1837 }
1838 return ReplaceInstUsesWith(I, NewPN);
1839}
1840
Chris Lattner2454a2e2008-01-29 06:52:45 +00001841
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001842/// WillNotOverflowSignedAdd - Return true if we can prove that:
1843/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1844/// This basically requires proving that the add in the original type would not
1845/// overflow to change the sign bit or have a carry out.
1846bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1847 // There are different heuristics we can use for this. Here are some simple
1848 // ones.
1849
1850 // Add has the property that adding any two 2's complement numbers can only
1851 // have one carry bit which can change a sign. As such, if LHS and RHS each
1852 // have at least two sign bits, we know that the addition of the two values will
1853 // sign extend fine.
1854 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1855 return true;
1856
1857
1858 // If one of the operands only has one non-zero bit, and if the other operand
1859 // has a known-zero bit in a more significant place than it (not including the
1860 // sign bit) the ripple may go up to and fill the zero, but won't change the
1861 // sign. For example, (X & ~4) + 1.
1862
1863 // TODO: Implement.
1864
1865 return false;
1866}
1867
Chris Lattner2454a2e2008-01-29 06:52:45 +00001868
Chris Lattner7e708292002-06-25 16:13:24 +00001869Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001870 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001871 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001872
Chris Lattner66331a42004-04-10 22:01:55 +00001873 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001874 // X + undef -> undef
1875 if (isa<UndefValue>(RHS))
1876 return ReplaceInstUsesWith(I, RHS);
1877
Chris Lattner66331a42004-04-10 22:01:55 +00001878 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001879 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001880 if (RHSC->isNullValue())
1881 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001882 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001883 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1884 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001885 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001886 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001887
Chris Lattner66331a42004-04-10 22:01:55 +00001888 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001889 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001890 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001891 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001892 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001893 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001894
1895 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1896 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001897 if (!isa<VectorType>(I.getType())) {
1898 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1899 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1900 KnownZero, KnownOne))
1901 return &I;
1902 }
Chris Lattner66331a42004-04-10 22:01:55 +00001903 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001904
1905 if (isa<PHINode>(LHS))
1906 if (Instruction *NV = FoldOpIntoPhi(I))
1907 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001908
Chris Lattner4f637d42006-01-06 17:59:59 +00001909 ConstantInt *XorRHS = 0;
1910 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001911 if (isa<ConstantInt>(RHSC) &&
1912 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00001913 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001914 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00001915
Zhou Sheng4351c642007-04-02 08:20:41 +00001916 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001917 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1918 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00001919 do {
1920 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00001921 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1922 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001923 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1924 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00001925 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00001926 if (!MaskedValueIsZero(XorLHS,
1927 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00001928 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001929 break;
Chris Lattner5931c542005-09-24 23:43:33 +00001930 }
1931 }
1932 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001933 C0080Val = APIntOps::lshr(C0080Val, Size);
1934 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1935 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00001936
Reid Spencer35c38852007-03-28 01:36:16 +00001937 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00001938 // with funny bit widths then this switch statement should be removed. It
1939 // is just here to get the size of the "middle" type back up to something
1940 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00001941 const Type *MiddleType = 0;
1942 switch (Size) {
1943 default: break;
1944 case 32: MiddleType = Type::Int32Ty; break;
1945 case 16: MiddleType = Type::Int16Ty; break;
1946 case 8: MiddleType = Type::Int8Ty; break;
1947 }
1948 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00001949 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00001950 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00001951 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00001952 }
1953 }
Chris Lattner66331a42004-04-10 22:01:55 +00001954 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001955
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001956 if (I.getType() == Type::Int1Ty)
1957 return BinaryOperator::CreateXor(LHS, RHS);
1958
Nick Lewycky7d26bd82008-05-23 04:39:38 +00001959 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001960 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001961 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001962
1963 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1964 if (RHSI->getOpcode() == Instruction::Sub)
1965 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1966 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1967 }
1968 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1969 if (LHSI->getOpcode() == Instruction::Sub)
1970 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1971 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1972 }
Robert Bocchino71698282004-07-27 21:02:21 +00001973 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001974
Chris Lattner5c4afb92002-05-08 22:46:53 +00001975 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00001976 // -A + -B --> -(A + B)
1977 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00001978 if (LHS->getType()->isIntOrIntVector()) {
1979 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001980 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00001981 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001982 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00001983 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00001984 }
1985
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001986 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00001987 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001988
1989 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00001990 if (!isa<Constant>(RHS))
1991 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001992 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001993
Misha Brukmanfd939082005-04-21 23:48:37 +00001994
Chris Lattner50af16a2004-11-13 19:50:12 +00001995 ConstantInt *C2;
1996 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1997 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001998 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00001999
2000 // X*C1 + X*C2 --> X * (C1+C2)
2001 ConstantInt *C1;
2002 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002003 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002004 }
2005
2006 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002007 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002008 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002009
Chris Lattnere617c9e2007-01-05 02:17:46 +00002010 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002011 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2012 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002013
Chris Lattnerad3448c2003-02-18 19:57:07 +00002014
Chris Lattner564a7272003-08-13 19:01:45 +00002015 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002016 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002017 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2018 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002019
2020 // A+B --> A|B iff A and B have no bits set in common.
2021 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2022 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2023 APInt LHSKnownOne(IT->getBitWidth(), 0);
2024 APInt LHSKnownZero(IT->getBitWidth(), 0);
2025 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2026 if (LHSKnownZero != 0) {
2027 APInt RHSKnownOne(IT->getBitWidth(), 0);
2028 APInt RHSKnownZero(IT->getBitWidth(), 0);
2029 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2030
2031 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002032 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002033 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002034 }
2035 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002036
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002037 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002038 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002039 Value *W, *X, *Y, *Z;
2040 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2041 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2042 if (W != Y) {
2043 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002044 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002045 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002046 std::swap(W, X);
2047 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002048 std::swap(Y, Z);
2049 std::swap(W, X);
2050 }
2051 }
2052
2053 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002054 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002055 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002056 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002057 }
2058 }
2059 }
2060
Chris Lattner6b032052003-10-02 15:11:26 +00002061 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002062 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002063 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002064 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002065
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002066 // (X & FF00) + xx00 -> (X+xx00) & FF00
2067 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002068 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002069 if (Anded == CRHS) {
2070 // See if all bits from the first bit set in the Add RHS up are included
2071 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002072 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002073
2074 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002075 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002076
2077 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002078 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002079
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002080 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2081 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002082 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002083 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002084 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002085 }
2086 }
2087 }
2088
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002089 // Try to fold constant add into select arguments.
2090 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002091 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002092 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002093 }
2094
Reid Spencer1628cec2006-10-26 06:15:43 +00002095 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002096 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002097 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002098 CastInst *CI = dyn_cast<CastInst>(LHS);
2099 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002100 if (!CI) {
2101 CI = dyn_cast<CastInst>(RHS);
2102 Other = LHS;
2103 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002104 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002105 (CI->getType()->getPrimitiveSizeInBits() ==
2106 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002107 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002108 unsigned AS =
2109 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002110 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2111 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002112 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002113 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002114 }
2115 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002116
Chris Lattner42790482007-12-20 01:56:58 +00002117 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002118 {
2119 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2120 Value *Other = RHS;
2121 if (!SI) {
2122 SI = dyn_cast<SelectInst>(RHS);
2123 Other = LHS;
2124 }
Chris Lattner42790482007-12-20 01:56:58 +00002125 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002126 Value *TV = SI->getTrueValue();
2127 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002128 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002129
2130 // Can we fold the add into the argument of the select?
2131 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002132 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2133 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002134 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002135 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2136 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002137 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002138 }
2139 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002140
2141 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2142 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2143 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2144 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002145
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002146 // Check for (add (sext x), y), see if we can merge this into an
2147 // integer add followed by a sext.
2148 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2149 // (add (sext x), cst) --> (sext (add x, cst'))
2150 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2151 Constant *CI =
2152 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2153 if (LHSConv->hasOneUse() &&
2154 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2155 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2156 // Insert the new, smaller add.
2157 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2158 CI, "addconv");
2159 InsertNewInstBefore(NewAdd, I);
2160 return new SExtInst(NewAdd, I.getType());
2161 }
2162 }
2163
2164 // (add (sext x), (sext y)) --> (sext (add int x, y))
2165 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2166 // Only do this if x/y have the same type, if at last one of them has a
2167 // single use (so we don't increase the number of sexts), and if the
2168 // integer add will not overflow.
2169 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2170 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2171 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2172 RHSConv->getOperand(0))) {
2173 // Insert the new integer add.
2174 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2175 RHSConv->getOperand(0),
2176 "addconv");
2177 InsertNewInstBefore(NewAdd, I);
2178 return new SExtInst(NewAdd, I.getType());
2179 }
2180 }
2181 }
2182
2183 // Check for (add double (sitofp x), y), see if we can merge this into an
2184 // integer add followed by a promotion.
2185 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2186 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2187 // ... if the constant fits in the integer value. This is useful for things
2188 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2189 // requires a constant pool load, and generally allows the add to be better
2190 // instcombined.
2191 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2192 Constant *CI =
2193 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2194 if (LHSConv->hasOneUse() &&
2195 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2196 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2197 // Insert the new integer add.
2198 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2199 CI, "addconv");
2200 InsertNewInstBefore(NewAdd, I);
2201 return new SIToFPInst(NewAdd, I.getType());
2202 }
2203 }
2204
2205 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2206 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2207 // Only do this if x/y have the same type, if at last one of them has a
2208 // single use (so we don't increase the number of int->fp conversions),
2209 // and if the integer add will not overflow.
2210 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2211 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2212 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2213 RHSConv->getOperand(0))) {
2214 // Insert the new integer add.
2215 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2216 RHSConv->getOperand(0),
2217 "addconv");
2218 InsertNewInstBefore(NewAdd, I);
2219 return new SIToFPInst(NewAdd, I.getType());
2220 }
2221 }
2222 }
2223
Chris Lattner7e708292002-06-25 16:13:24 +00002224 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002225}
2226
Chris Lattner7e708292002-06-25 16:13:24 +00002227Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002228 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002229
Chris Lattner233f7dc2002-08-12 21:17:25 +00002230 if (Op0 == Op1) // sub X, X -> 0
2231 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002232
Chris Lattner233f7dc2002-08-12 21:17:25 +00002233 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002234 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002235 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002236
Chris Lattnere87597f2004-10-16 18:11:37 +00002237 if (isa<UndefValue>(Op0))
2238 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2239 if (isa<UndefValue>(Op1))
2240 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2241
Chris Lattnerd65460f2003-11-05 01:06:05 +00002242 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2243 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002244 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002245 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002246
Chris Lattnerd65460f2003-11-05 01:06:05 +00002247 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002248 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002249 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002250 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002251
Chris Lattner76b7a062007-01-15 07:02:54 +00002252 // -(X >>u 31) -> (X >>s 31)
2253 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002254 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002255 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002256 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002257 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002258 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002259 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002260 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002261 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002262 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002263 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002264 }
2265 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002266 }
2267 else if (SI->getOpcode() == Instruction::AShr) {
2268 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2269 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002270 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002271 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002272 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002273 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002274 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002275 }
2276 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002277 }
2278 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002279 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002280
2281 // Try to fold constant sub into select arguments.
2282 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002283 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002284 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002285
2286 if (isa<PHINode>(Op0))
2287 if (Instruction *NV = FoldOpIntoPhi(I))
2288 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002289 }
2290
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002291 if (I.getType() == Type::Int1Ty)
2292 return BinaryOperator::CreateXor(Op0, Op1);
2293
Chris Lattner43d84d62005-04-07 16:15:25 +00002294 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2295 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002296 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002297 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002298 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002299 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002300 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002301 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2302 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2303 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002304 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002305 Op1I->getOperand(0));
2306 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002307 }
2308
Chris Lattnerfd059242003-10-15 16:48:29 +00002309 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002310 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2311 // is not used by anyone else...
2312 //
Chris Lattner0517e722004-02-02 20:09:56 +00002313 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002314 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002315 // Swap the two operands of the subexpr...
2316 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2317 Op1I->setOperand(0, IIOp1);
2318 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002319
Chris Lattnera2881962003-02-18 19:28:33 +00002320 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002321 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002322 }
2323
2324 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2325 //
2326 if (Op1I->getOpcode() == Instruction::And &&
2327 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2328 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2329
Chris Lattnerf523d062004-06-09 05:08:07 +00002330 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002331 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2332 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002333 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002334
Reid Spencerac5209e2006-10-16 23:08:08 +00002335 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002336 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002337 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002338 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002339 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002340 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002341 ConstantExpr::getNeg(DivRHS));
2342
Chris Lattnerad3448c2003-02-18 19:57:07 +00002343 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002344 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002345 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002346 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002347 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002348 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002349
2350 // X - ((X / Y) * Y) --> X % Y
2351 if (Op1I->getOpcode() == Instruction::Mul)
2352 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2353 if (Op0 == I->getOperand(0) &&
2354 Op1I->getOperand(1) == I->getOperand(1)) {
2355 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002356 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002357 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002358 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002359 }
Chris Lattner40371712002-05-09 01:29:19 +00002360 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002361 }
Chris Lattnera2881962003-02-18 19:28:33 +00002362
Chris Lattner9919e3d2006-12-02 00:13:08 +00002363 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002364 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002365 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002366 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2367 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2368 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2369 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002370 } else if (Op0I->getOpcode() == Instruction::Sub) {
2371 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002372 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002373 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002374 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002375
Chris Lattner50af16a2004-11-13 19:50:12 +00002376 ConstantInt *C1;
2377 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002378 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002379 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002380
Chris Lattner50af16a2004-11-13 19:50:12 +00002381 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2382 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002383 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002384 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002385 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002386}
2387
Chris Lattnera0141b92007-07-15 20:42:37 +00002388/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2389/// comparison only checks the sign bit. If it only checks the sign bit, set
2390/// TrueIfSigned if the result of the comparison is true when the input value is
2391/// signed.
2392static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2393 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002394 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002395 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2396 TrueIfSigned = true;
2397 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002398 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2399 TrueIfSigned = true;
2400 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002401 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2402 TrueIfSigned = false;
2403 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002404 case ICmpInst::ICMP_UGT:
2405 // True if LHS u> RHS and RHS == high-bit-mask - 1
2406 TrueIfSigned = true;
2407 return RHS->getValue() ==
2408 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2409 case ICmpInst::ICMP_UGE:
2410 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2411 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002412 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002413 default:
2414 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002415 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002416}
2417
Chris Lattner7e708292002-06-25 16:13:24 +00002418Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002419 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002420 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002421
Chris Lattnere87597f2004-10-16 18:11:37 +00002422 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2423 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2424
Chris Lattner233f7dc2002-08-12 21:17:25 +00002425 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002426 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2427 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002428
2429 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002430 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002431 if (SI->getOpcode() == Instruction::Shl)
2432 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002433 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002434 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002435
Zhou Sheng843f07672007-04-19 05:39:12 +00002436 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002437 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2438 if (CI->equalsInt(1)) // X * 1 == X
2439 return ReplaceInstUsesWith(I, Op0);
2440 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002441 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002442
Zhou Sheng97b52c22007-03-29 01:57:21 +00002443 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002444 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002445 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002446 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002447 }
Robert Bocchino71698282004-07-27 21:02:21 +00002448 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002449 if (Op1F->isNullValue())
2450 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002451
Chris Lattnera2881962003-02-18 19:28:33 +00002452 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2453 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002454 // We need a better interface for long double here.
2455 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2456 if (Op1F->isExactlyValue(1.0))
2457 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002458 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002459
2460 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2461 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002462 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002463 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002464 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002465 Op1, "tmp");
2466 InsertNewInstBefore(Add, I);
2467 Value *C1C2 = ConstantExpr::getMul(Op1,
2468 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002469 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002470
2471 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002472
2473 // Try to fold constant mul into select arguments.
2474 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002475 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002476 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002477
2478 if (isa<PHINode>(Op0))
2479 if (Instruction *NV = FoldOpIntoPhi(I))
2480 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002481 }
2482
Chris Lattnera4f445b2003-03-10 23:23:04 +00002483 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2484 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002485 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002486
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002487 if (I.getType() == Type::Int1Ty)
2488 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2489
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002490 // If one of the operands of the multiply is a cast from a boolean value, then
2491 // we know the bool is either zero or one, so this is a 'masking' multiply.
2492 // See if we can simplify things based on how the boolean was originally
2493 // formed.
2494 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002495 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002496 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002497 BoolCast = CI;
2498 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002499 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002500 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002501 BoolCast = CI;
2502 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002503 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002504 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2505 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002506 bool TIS = false;
2507
Reid Spencere4d87aa2006-12-23 06:05:41 +00002508 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002509 // multiply into a shift/and combination.
2510 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002511 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2512 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002513 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002514 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002515 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002516 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002517 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002518 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002519 BoolCast->getOperand(0)->getName()+
2520 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002521
2522 // If the multiply type is not the same as the source type, sign extend
2523 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002524 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002525 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2526 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002527 Instruction::CastOps opcode =
2528 (SrcBits == DstBits ? Instruction::BitCast :
2529 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2530 V = InsertCastBefore(opcode, V, I.getType(), I);
2531 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002532
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002533 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002534 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002535 }
2536 }
2537 }
2538
Chris Lattner7e708292002-06-25 16:13:24 +00002539 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002540}
2541
Reid Spencer1628cec2006-10-26 06:15:43 +00002542/// This function implements the transforms on div instructions that work
2543/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2544/// used by the visitors to those instructions.
2545/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002546Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002547 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002548
Chris Lattner50b2ca42008-02-19 06:12:18 +00002549 // undef / X -> 0 for integer.
2550 // undef / X -> undef for FP (the undef could be a snan).
2551 if (isa<UndefValue>(Op0)) {
2552 if (Op0->getType()->isFPOrFPVector())
2553 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002554 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002555 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002556
2557 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002558 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002559 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002560
Chris Lattner25feae52008-01-28 00:58:18 +00002561 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2562 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002563 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002564 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2565 // the same basic block, then we replace the select with Y, and the
2566 // condition of the select with false (if the cond value is in the same BB).
2567 // If the select has uses other than the div, this allows them to be
2568 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2569 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002570 if (ST->isNullValue()) {
2571 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2572 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002573 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002574 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2575 I.setOperand(1, SI->getOperand(2));
2576 else
2577 UpdateValueUsesWith(SI, SI->getOperand(2));
2578 return &I;
2579 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002580
Chris Lattner25feae52008-01-28 00:58:18 +00002581 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2582 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002583 if (ST->isNullValue()) {
2584 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2585 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002586 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002587 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2588 I.setOperand(1, SI->getOperand(1));
2589 else
2590 UpdateValueUsesWith(SI, SI->getOperand(1));
2591 return &I;
2592 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002593 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002594
Reid Spencer1628cec2006-10-26 06:15:43 +00002595 return 0;
2596}
Misha Brukmanfd939082005-04-21 23:48:37 +00002597
Reid Spencer1628cec2006-10-26 06:15:43 +00002598/// This function implements the transforms common to both integer division
2599/// instructions (udiv and sdiv). It is called by the visitors to those integer
2600/// division instructions.
2601/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002602Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002603 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2604
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002605 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002606 if (Op0 == Op1) {
2607 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2608 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2609 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2610 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2611 }
2612
2613 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2614 return ReplaceInstUsesWith(I, CI);
2615 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002616
Reid Spencer1628cec2006-10-26 06:15:43 +00002617 if (Instruction *Common = commonDivTransforms(I))
2618 return Common;
2619
2620 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2621 // div X, 1 == X
2622 if (RHS->equalsInt(1))
2623 return ReplaceInstUsesWith(I, Op0);
2624
2625 // (X / C1) / C2 -> X / (C1*C2)
2626 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2627 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2628 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002629 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2630 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2631 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002632 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002633 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002634 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002635
Reid Spencerbca0e382007-03-23 20:05:17 +00002636 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002637 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2638 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2639 return R;
2640 if (isa<PHINode>(Op0))
2641 if (Instruction *NV = FoldOpIntoPhi(I))
2642 return NV;
2643 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002644 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002645
Chris Lattnera2881962003-02-18 19:28:33 +00002646 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002647 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002648 if (LHS->equalsInt(0))
2649 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2650
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002651 // It can't be division by zero, hence it must be division by one.
2652 if (I.getType() == Type::Int1Ty)
2653 return ReplaceInstUsesWith(I, Op0);
2654
Reid Spencer1628cec2006-10-26 06:15:43 +00002655 return 0;
2656}
2657
2658Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2659 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2660
2661 // Handle the integer div common cases
2662 if (Instruction *Common = commonIDivTransforms(I))
2663 return Common;
2664
2665 // X udiv C^2 -> X >> C
2666 // Check to see if this is an unsigned division with an exact power of 2,
2667 // if so, convert to a right shift.
2668 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002669 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002670 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002671 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002672 }
2673
2674 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002675 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002676 if (RHSI->getOpcode() == Instruction::Shl &&
2677 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002678 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002679 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002680 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002681 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002682 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002683 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002684 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002685 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002686 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002687 }
2688 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002689 }
2690
Reid Spencer1628cec2006-10-26 06:15:43 +00002691 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2692 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002693 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002694 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002695 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002696 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002697 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002698 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002699 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002700 // Construct the "on true" case of the select
2701 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002702 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002703 Op0, TC, SI->getName()+".t");
2704 TSI = InsertNewInstBefore(TSI, I);
2705
2706 // Construct the "on false" case of the select
2707 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002708 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002709 Op0, FC, SI->getName()+".f");
2710 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002711
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002712 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002713 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002714 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002715 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002716 return 0;
2717}
2718
Reid Spencer1628cec2006-10-26 06:15:43 +00002719Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2720 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2721
2722 // Handle the integer div common cases
2723 if (Instruction *Common = commonIDivTransforms(I))
2724 return Common;
2725
2726 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2727 // sdiv X, -1 == -X
2728 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002729 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002730
2731 // -X/C -> X/-C
2732 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002733 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00002734 }
2735
2736 // If the sign bits of both operands are zero (i.e. we can prove they are
2737 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002738 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002739 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002740 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002741 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002742 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002743 }
2744 }
2745
2746 return 0;
2747}
2748
2749Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2750 return commonDivTransforms(I);
2751}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002752
Reid Spencer0a783f72006-11-02 01:53:59 +00002753/// This function implements the transforms on rem instructions that work
2754/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2755/// is used by the visitors to those instructions.
2756/// @brief Transforms common to all three rem instructions
2757Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002758 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002759
Chris Lattner50b2ca42008-02-19 06:12:18 +00002760 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002761 if (Constant *LHS = dyn_cast<Constant>(Op0))
2762 if (LHS->isNullValue())
2763 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2764
Chris Lattner50b2ca42008-02-19 06:12:18 +00002765 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2766 if (I.getType()->isFPOrFPVector())
2767 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002768 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002769 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002770 if (isa<UndefValue>(Op1))
2771 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002772
2773 // Handle cases involving: rem X, (select Cond, Y, Z)
2774 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2775 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2776 // the same basic block, then we replace the select with Y, and the
2777 // condition of the select with false (if the cond value is in the same
2778 // BB). If the select has uses other than the div, this allows them to be
2779 // simplified also.
2780 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2781 if (ST->isNullValue()) {
2782 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2783 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002784 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002785 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2786 I.setOperand(1, SI->getOperand(2));
2787 else
2788 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002789 return &I;
2790 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002791 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2792 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2793 if (ST->isNullValue()) {
2794 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2795 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002796 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002797 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2798 I.setOperand(1, SI->getOperand(1));
2799 else
2800 UpdateValueUsesWith(SI, SI->getOperand(1));
2801 return &I;
2802 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002803 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002804
Reid Spencer0a783f72006-11-02 01:53:59 +00002805 return 0;
2806}
2807
2808/// This function implements the transforms common to both integer remainder
2809/// instructions (urem and srem). It is called by the visitors to those integer
2810/// remainder instructions.
2811/// @brief Common integer remainder transforms
2812Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2813 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2814
2815 if (Instruction *common = commonRemTransforms(I))
2816 return common;
2817
Chris Lattner857e8cd2004-12-12 21:48:58 +00002818 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002819 // X % 0 == undef, we don't need to preserve faults!
2820 if (RHS->equalsInt(0))
2821 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2822
Chris Lattnera2881962003-02-18 19:28:33 +00002823 if (RHS->equalsInt(1)) // X % 1 == 0
2824 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2825
Chris Lattner97943922006-02-28 05:49:21 +00002826 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2827 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2828 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2829 return R;
2830 } else if (isa<PHINode>(Op0I)) {
2831 if (Instruction *NV = FoldOpIntoPhi(I))
2832 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002833 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002834
2835 // See if we can fold away this rem instruction.
2836 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2837 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2838 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2839 KnownZero, KnownOne))
2840 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002841 }
Chris Lattnera2881962003-02-18 19:28:33 +00002842 }
2843
Reid Spencer0a783f72006-11-02 01:53:59 +00002844 return 0;
2845}
2846
2847Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2848 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2849
2850 if (Instruction *common = commonIRemTransforms(I))
2851 return common;
2852
2853 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2854 // X urem C^2 -> X and C
2855 // Check to see if this is an unsigned remainder with an exact power of 2,
2856 // if so, convert to a bitwise and.
2857 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002858 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002859 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00002860 }
2861
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002862 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002863 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2864 if (RHSI->getOpcode() == Instruction::Shl &&
2865 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002866 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002867 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002868 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002869 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002870 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002871 }
2872 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002873 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002874
Reid Spencer0a783f72006-11-02 01:53:59 +00002875 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2876 // where C1&C2 are powers of two.
2877 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2878 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2879 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2880 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002881 if ((STO->getValue().isPowerOf2()) &&
2882 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002883 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002884 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00002885 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002886 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002887 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00002888 }
2889 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002890 }
2891
Chris Lattner3f5b8772002-05-06 16:14:14 +00002892 return 0;
2893}
2894
Reid Spencer0a783f72006-11-02 01:53:59 +00002895Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2896 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2897
Dan Gohmancff55092007-11-05 23:16:33 +00002898 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002899 if (Instruction *common = commonIRemTransforms(I))
2900 return common;
2901
2902 if (Value *RHSNeg = dyn_castNegVal(Op1))
2903 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002904 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002905 // X % -Y -> X % Y
2906 AddUsesToWorkList(I);
2907 I.setOperand(1, RHSNeg);
2908 return &I;
2909 }
2910
Dan Gohmancff55092007-11-05 23:16:33 +00002911 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002912 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002913 if (I.getType()->isInteger()) {
2914 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2915 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2916 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002917 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00002918 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002919 }
2920
2921 return 0;
2922}
2923
2924Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002925 return commonRemTransforms(I);
2926}
2927
Chris Lattner8b170942002-08-09 23:47:40 +00002928// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002929static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002930 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00002931 if (!isSigned)
2932 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2933 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002934}
2935
2936// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002937static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002938 if (!isSigned)
2939 return C->getValue() == 1; // unsigned
2940
2941 // Calculate 1111111111000000000000
2942 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2943 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002944}
2945
Chris Lattner457dd822004-06-09 07:59:58 +00002946// isOneBitSet - Return true if there is exactly one bit set in the specified
2947// constant.
2948static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002949 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002950}
2951
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002952// isHighOnes - Return true if the constant is of the form 1+0+.
2953// This is the same as lowones(~X).
2954static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002955 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002956}
2957
Reid Spencere4d87aa2006-12-23 06:05:41 +00002958/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002959/// are carefully arranged to allow folding of expressions such as:
2960///
2961/// (A < B) | (A > B) --> (A != B)
2962///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002963/// Note that this is only valid if the first and second predicates have the
2964/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002965///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002966/// Three bits are used to represent the condition, as follows:
2967/// 0 A > B
2968/// 1 A == B
2969/// 2 A < B
2970///
2971/// <=> Value Definition
2972/// 000 0 Always false
2973/// 001 1 A > B
2974/// 010 2 A == B
2975/// 011 3 A >= B
2976/// 100 4 A < B
2977/// 101 5 A != B
2978/// 110 6 A <= B
2979/// 111 7 Always true
2980///
2981static unsigned getICmpCode(const ICmpInst *ICI) {
2982 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002983 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00002984 case ICmpInst::ICMP_UGT: return 1; // 001
2985 case ICmpInst::ICMP_SGT: return 1; // 001
2986 case ICmpInst::ICMP_EQ: return 2; // 010
2987 case ICmpInst::ICMP_UGE: return 3; // 011
2988 case ICmpInst::ICMP_SGE: return 3; // 011
2989 case ICmpInst::ICMP_ULT: return 4; // 100
2990 case ICmpInst::ICMP_SLT: return 4; // 100
2991 case ICmpInst::ICMP_NE: return 5; // 101
2992 case ICmpInst::ICMP_ULE: return 6; // 110
2993 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002994 // True -> 7
2995 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00002996 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002997 return 0;
2998 }
2999}
3000
Reid Spencere4d87aa2006-12-23 06:05:41 +00003001/// getICmpValue - This is the complement of getICmpCode, which turns an
3002/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003003/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003004/// of predicate to use in new icmp instructions.
3005static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3006 switch (code) {
3007 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003008 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003009 case 1:
3010 if (sign)
3011 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3012 else
3013 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3014 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3015 case 3:
3016 if (sign)
3017 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3018 else
3019 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3020 case 4:
3021 if (sign)
3022 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3023 else
3024 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3025 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3026 case 6:
3027 if (sign)
3028 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3029 else
3030 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003031 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003032 }
3033}
3034
Reid Spencere4d87aa2006-12-23 06:05:41 +00003035static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3036 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3037 (ICmpInst::isSignedPredicate(p1) &&
3038 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3039 (ICmpInst::isSignedPredicate(p2) &&
3040 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3041}
3042
3043namespace {
3044// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3045struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003046 InstCombiner &IC;
3047 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003048 ICmpInst::Predicate pred;
3049 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3050 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3051 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003052 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003053 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3054 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003055 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3056 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003057 return false;
3058 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003059 Instruction *apply(Instruction &Log) const {
3060 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3061 if (ICI->getOperand(0) != LHS) {
3062 assert(ICI->getOperand(1) == LHS);
3063 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003064 }
3065
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003066 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003067 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003068 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003069 unsigned Code;
3070 switch (Log.getOpcode()) {
3071 case Instruction::And: Code = LHSCode & RHSCode; break;
3072 case Instruction::Or: Code = LHSCode | RHSCode; break;
3073 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003074 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003075 }
3076
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003077 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3078 ICmpInst::isSignedPredicate(ICI->getPredicate());
3079
3080 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003081 if (Instruction *I = dyn_cast<Instruction>(RV))
3082 return I;
3083 // Otherwise, it's a constant boolean value...
3084 return IC.ReplaceInstUsesWith(Log, RV);
3085 }
3086};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003087} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003088
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003089// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3090// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003091// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003092Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003093 ConstantInt *OpRHS,
3094 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003095 BinaryOperator &TheAnd) {
3096 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003097 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003098 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003099 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003100
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003101 switch (Op->getOpcode()) {
3102 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003103 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003104 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003105 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003106 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003107 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003108 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003109 }
3110 break;
3111 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003112 if (Together == AndRHS) // (X | C) & C --> C
3113 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003114
Chris Lattner6e7ba452005-01-01 16:22:27 +00003115 if (Op->hasOneUse() && Together != OpRHS) {
3116 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003117 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003118 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003119 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003120 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003121 }
3122 break;
3123 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003124 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003125 // Adding a one to a single bit bit-field should be turned into an XOR
3126 // of the bit. First thing to check is to see if this AND is with a
3127 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003128 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003129
3130 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003131 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003132 // Ok, at this point, we know that we are masking the result of the
3133 // ADD down to exactly one bit. If the constant we are adding has
3134 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003135 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003136
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003137 // Check to see if any bits below the one bit set in AndRHSV are set.
3138 if ((AddRHS & (AndRHSV-1)) == 0) {
3139 // If not, the only thing that can effect the output of the AND is
3140 // the bit specified by AndRHSV. If that bit is set, the effect of
3141 // the XOR is to toggle the bit. If it is clear, then the ADD has
3142 // no effect.
3143 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3144 TheAnd.setOperand(0, X);
3145 return &TheAnd;
3146 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003147 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003148 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003149 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003150 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003151 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003152 }
3153 }
3154 }
3155 }
3156 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003157
3158 case Instruction::Shl: {
3159 // We know that the AND will not produce any of the bits shifted in, so if
3160 // the anded constant includes them, clear them now!
3161 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003162 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003163 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003164 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3165 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003166
Zhou Sheng290bec52007-03-29 08:15:12 +00003167 if (CI->getValue() == ShlMask) {
3168 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003169 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3170 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003171 TheAnd.setOperand(1, CI);
3172 return &TheAnd;
3173 }
3174 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003175 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003176 case Instruction::LShr:
3177 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003178 // We know that the AND will not produce any of the bits shifted in, so if
3179 // the anded constant includes them, clear them now! This only applies to
3180 // unsigned shifts, because a signed shr may bring in set bits!
3181 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003182 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003183 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003184 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3185 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003186
Zhou Sheng290bec52007-03-29 08:15:12 +00003187 if (CI->getValue() == ShrMask) {
3188 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003189 return ReplaceInstUsesWith(TheAnd, Op);
3190 } else if (CI != AndRHS) {
3191 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3192 return &TheAnd;
3193 }
3194 break;
3195 }
3196 case Instruction::AShr:
3197 // Signed shr.
3198 // See if this is shifting in some sign extension, then masking it out
3199 // with an and.
3200 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003201 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003202 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003203 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3204 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003205 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003206 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003207 // Make the argument unsigned.
3208 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003209 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003210 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003211 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003212 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003213 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003214 }
3215 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003216 }
3217 return 0;
3218}
3219
Chris Lattner8b170942002-08-09 23:47:40 +00003220
Chris Lattnera96879a2004-09-29 17:40:11 +00003221/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3222/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003223/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3224/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003225/// insert new instructions.
3226Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003227 bool isSigned, bool Inside,
3228 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003229 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003230 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003231 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003232
Chris Lattnera96879a2004-09-29 17:40:11 +00003233 if (Inside) {
3234 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003235 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003236
Reid Spencere4d87aa2006-12-23 06:05:41 +00003237 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003238 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003239 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003240 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3241 return new ICmpInst(pred, V, Hi);
3242 }
3243
3244 // Emit V-Lo <u Hi-Lo
3245 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003246 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003247 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003248 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3249 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003250 }
3251
3252 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003253 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003254
Reid Spencere4e40032007-03-21 23:19:50 +00003255 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003256 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003257 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003258 ICmpInst::Predicate pred = (isSigned ?
3259 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3260 return new ICmpInst(pred, V, Hi);
3261 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003262
Reid Spencere4e40032007-03-21 23:19:50 +00003263 // Emit V-Lo >u Hi-1-Lo
3264 // Note that Hi has already had one subtracted from it, above.
3265 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003266 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003267 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003268 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3269 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003270}
3271
Chris Lattner7203e152005-09-18 07:22:02 +00003272// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3273// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3274// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3275// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003276static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003277 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003278 uint32_t BitWidth = Val->getType()->getBitWidth();
3279 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003280
3281 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003282 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003283 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003284 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003285 return true;
3286}
3287
Chris Lattner7203e152005-09-18 07:22:02 +00003288/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3289/// where isSub determines whether the operator is a sub. If we can fold one of
3290/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003291///
3292/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3293/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3294/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3295///
3296/// return (A +/- B).
3297///
3298Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003299 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003300 Instruction &I) {
3301 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3302 if (!LHSI || LHSI->getNumOperands() != 2 ||
3303 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3304
3305 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3306
3307 switch (LHSI->getOpcode()) {
3308 default: return 0;
3309 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003310 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003311 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003312 if ((Mask->getValue().countLeadingZeros() +
3313 Mask->getValue().countPopulation()) ==
3314 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003315 break;
3316
3317 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3318 // part, we don't need any explicit masks to take them out of A. If that
3319 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003320 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003321 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003322 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003323 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003324 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003325 break;
3326 }
3327 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003328 return 0;
3329 case Instruction::Or:
3330 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003331 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003332 if ((Mask->getValue().countLeadingZeros() +
3333 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003334 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003335 break;
3336 return 0;
3337 }
3338
3339 Instruction *New;
3340 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003341 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003342 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003343 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003344 return InsertNewInstBefore(New, I);
3345}
3346
Chris Lattner7e708292002-06-25 16:13:24 +00003347Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003348 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003349 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003350
Chris Lattnere87597f2004-10-16 18:11:37 +00003351 if (isa<UndefValue>(Op1)) // X & undef -> 0
3352 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3353
Chris Lattner6e7ba452005-01-01 16:22:27 +00003354 // and X, X = X
3355 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003356 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003357
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003358 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003359 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003360 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003361 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3362 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3363 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003364 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003365 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003366 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003367 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003368 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003369 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003370 } else if (isa<ConstantAggregateZero>(Op1)) {
3371 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003372 }
3373 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003374
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003375 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003376 const APInt& AndRHSMask = AndRHS->getValue();
3377 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003378
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003379 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003380 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003381 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003382 Value *Op0LHS = Op0I->getOperand(0);
3383 Value *Op0RHS = Op0I->getOperand(1);
3384 switch (Op0I->getOpcode()) {
3385 case Instruction::Xor:
3386 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003387 // If the mask is only needed on one incoming arm, push it up.
3388 if (Op0I->hasOneUse()) {
3389 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3390 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003391 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003392 Op0RHS->getName()+".masked");
3393 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003394 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003395 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003396 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003397 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003398 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3399 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003400 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003401 Op0LHS->getName()+".masked");
3402 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003403 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003404 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3405 }
3406 }
3407
Chris Lattner6e7ba452005-01-01 16:22:27 +00003408 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003409 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003410 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3411 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3412 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3413 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003414 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003415 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003416 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003417 break;
3418
3419 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003420 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3421 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3422 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3423 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003424 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003425 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003426 }
3427
Chris Lattner58403262003-07-23 19:25:52 +00003428 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003429 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003430 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003431 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003432 // If this is an integer truncation or change from signed-to-unsigned, and
3433 // if the source is an and/or with immediate, transform it. This
3434 // frequently occurs for bitfield accesses.
3435 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003436 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003437 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003438 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003439 if (CastOp->getOpcode() == Instruction::And) {
3440 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003441 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3442 // This will fold the two constants together, which may allow
3443 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003444 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003445 CastOp->getOperand(0), I.getType(),
3446 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003447 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003448 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003449 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003450 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003451 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003452 } else if (CastOp->getOpcode() == Instruction::Or) {
3453 // Change: and (cast (or X, C1) to T), C2
3454 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003455 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003456 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3457 return ReplaceInstUsesWith(I, AndRHS);
3458 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003459 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003460 }
Chris Lattner06782f82003-07-23 19:36:21 +00003461 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003462
3463 // Try to fold constant and into select arguments.
3464 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003465 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003466 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003467 if (isa<PHINode>(Op0))
3468 if (Instruction *NV = FoldOpIntoPhi(I))
3469 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003470 }
3471
Chris Lattner8d969642003-03-10 23:06:50 +00003472 Value *Op0NotVal = dyn_castNotVal(Op0);
3473 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003474
Chris Lattner5b62aa72004-06-18 06:07:51 +00003475 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3476 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3477
Misha Brukmancb6267b2004-07-30 12:50:08 +00003478 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003479 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003480 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003481 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003482 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003483 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003484 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003485
3486 {
Chris Lattner003b6202007-06-15 05:58:24 +00003487 Value *A = 0, *B = 0, *C = 0, *D = 0;
3488 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003489 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3490 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003491
3492 // (A|B) & ~(A&B) -> A^B
3493 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3494 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003495 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003496 }
3497 }
3498
3499 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003500 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3501 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003502
3503 // ~(A&B) & (A|B) -> A^B
3504 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3505 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003506 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003507 }
3508 }
Chris Lattner64daab52006-04-01 08:03:55 +00003509
3510 if (Op0->hasOneUse() &&
3511 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3512 if (A == Op1) { // (A^B)&A -> A&(A^B)
3513 I.swapOperands(); // Simplify below
3514 std::swap(Op0, Op1);
3515 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3516 cast<BinaryOperator>(Op0)->swapOperands();
3517 I.swapOperands(); // Simplify below
3518 std::swap(Op0, Op1);
3519 }
3520 }
3521 if (Op1->hasOneUse() &&
3522 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3523 if (B == Op0) { // B&(A^B) -> B&(B^A)
3524 cast<BinaryOperator>(Op1)->swapOperands();
3525 std::swap(A, B);
3526 }
3527 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003528 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003529 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003530 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003531 }
3532 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003533 }
3534
Reid Spencere4d87aa2006-12-23 06:05:41 +00003535 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3536 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3537 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003538 return R;
3539
Chris Lattner955f3312004-09-28 21:48:02 +00003540 Value *LHSVal, *RHSVal;
3541 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003542 ICmpInst::Predicate LHSCC, RHSCC;
3543 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3544 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3545 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3546 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3547 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3548 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3549 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003550 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3551
3552 // Don't try to fold ICMP_SLT + ICMP_ULT.
3553 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3554 ICmpInst::isSignedPredicate(LHSCC) ==
3555 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003556 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003557 ICmpInst::Predicate GT;
3558 if (ICmpInst::isSignedPredicate(LHSCC) ||
3559 (ICmpInst::isEquality(LHSCC) &&
3560 ICmpInst::isSignedPredicate(RHSCC)))
3561 GT = ICmpInst::ICMP_SGT;
3562 else
3563 GT = ICmpInst::ICMP_UGT;
3564
Reid Spencere4d87aa2006-12-23 06:05:41 +00003565 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3566 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003567 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003568 std::swap(LHS, RHS);
3569 std::swap(LHSCst, RHSCst);
3570 std::swap(LHSCC, RHSCC);
3571 }
3572
Reid Spencere4d87aa2006-12-23 06:05:41 +00003573 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003574 // comparing a value against two constants and and'ing the result
3575 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003576 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3577 // (from the FoldICmpLogical check above), that the two constants
3578 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003579 assert(LHSCst != RHSCst && "Compares not folded above?");
3580
3581 switch (LHSCC) {
3582 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003583 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003584 switch (RHSCC) {
3585 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003586 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3587 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3588 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003589 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003590 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3591 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3592 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003593 return ReplaceInstUsesWith(I, LHS);
3594 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003595 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003596 switch (RHSCC) {
3597 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003598 case ICmpInst::ICMP_ULT:
3599 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3600 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3601 break; // (X != 13 & X u< 15) -> no change
3602 case ICmpInst::ICMP_SLT:
3603 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3604 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3605 break; // (X != 13 & X s< 15) -> no change
3606 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3607 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3608 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003609 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003610 case ICmpInst::ICMP_NE:
3611 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003612 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003613 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00003614 LHSVal->getName()+".off");
3615 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003616 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3617 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003618 }
3619 break; // (X != 13 & X != 15) -> no change
3620 }
3621 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003622 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003623 switch (RHSCC) {
3624 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003625 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3626 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003627 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003628 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3629 break;
3630 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3631 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003632 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003633 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3634 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003635 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003636 break;
3637 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003638 switch (RHSCC) {
3639 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003640 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3641 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003642 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003643 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3644 break;
3645 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3646 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003647 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003648 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3649 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003650 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003651 break;
3652 case ICmpInst::ICMP_UGT:
3653 switch (RHSCC) {
3654 default: assert(0 && "Unknown integer condition code!");
3655 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3656 return ReplaceInstUsesWith(I, LHS);
3657 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3658 return ReplaceInstUsesWith(I, RHS);
3659 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3660 break;
3661 case ICmpInst::ICMP_NE:
3662 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3663 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3664 break; // (X u> 13 & X != 15) -> no change
3665 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3666 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3667 true, I);
3668 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3669 break;
3670 }
3671 break;
3672 case ICmpInst::ICMP_SGT:
3673 switch (RHSCC) {
3674 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003675 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003676 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3677 return ReplaceInstUsesWith(I, RHS);
3678 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3679 break;
3680 case ICmpInst::ICMP_NE:
3681 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3682 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3683 break; // (X s> 13 & X != 15) -> no change
3684 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3685 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3686 true, I);
3687 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3688 break;
3689 }
3690 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003691 }
3692 }
3693 }
3694
Chris Lattner6fc205f2006-05-05 06:39:07 +00003695 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003696 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3697 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3698 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3699 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003700 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003701 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003702 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3703 I.getType(), TD) &&
3704 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3705 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003706 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003707 Op1C->getOperand(0),
3708 I.getName());
3709 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003710 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003711 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003712 }
Chris Lattnere511b742006-11-14 07:46:50 +00003713
3714 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003715 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3716 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3717 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003718 SI0->getOperand(1) == SI1->getOperand(1) &&
3719 (SI0->hasOneUse() || SI1->hasOneUse())) {
3720 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003721 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00003722 SI1->getOperand(0),
3723 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003724 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003725 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003726 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003727 }
3728
Chris Lattner99c65742007-10-24 05:38:08 +00003729 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3730 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3731 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3732 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3733 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3734 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3735 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3736 // If either of the constants are nans, then the whole thing returns
3737 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003738 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003739 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3740 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3741 RHS->getOperand(0));
3742 }
3743 }
3744 }
3745
Chris Lattner7e708292002-06-25 16:13:24 +00003746 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003747}
3748
Chris Lattnerafe91a52006-06-15 19:07:26 +00003749/// CollectBSwapParts - Look to see if the specified value defines a single byte
3750/// in the result. If it does, and if the specified byte hasn't been filled in
3751/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003752static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003753 Instruction *I = dyn_cast<Instruction>(V);
3754 if (I == 0) return true;
3755
3756 // If this is an or instruction, it is an inner node of the bswap.
3757 if (I->getOpcode() == Instruction::Or)
3758 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3759 CollectBSwapParts(I->getOperand(1), ByteValues);
3760
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003761 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003762 // If this is a shift by a constant int, and it is "24", then its operand
3763 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003764 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003765 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003766 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003767 8*(ByteValues.size()-1))
3768 return true;
3769
3770 unsigned DestNo;
3771 if (I->getOpcode() == Instruction::Shl) {
3772 // X << 24 defines the top byte with the lowest of the input bytes.
3773 DestNo = ByteValues.size()-1;
3774 } else {
3775 // X >>u 24 defines the low byte with the highest of the input bytes.
3776 DestNo = 0;
3777 }
3778
3779 // If the destination byte value is already defined, the values are or'd
3780 // together, which isn't a bswap (unless it's an or of the same bits).
3781 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3782 return true;
3783 ByteValues[DestNo] = I->getOperand(0);
3784 return false;
3785 }
3786
3787 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3788 // don't have this.
3789 Value *Shift = 0, *ShiftLHS = 0;
3790 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3791 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3792 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3793 return true;
3794 Instruction *SI = cast<Instruction>(Shift);
3795
3796 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003797 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3798 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003799 return true;
3800
3801 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3802 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003803 if (AndAmt->getValue().getActiveBits() > 64)
3804 return true;
3805 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003806 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003807 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003808 break;
3809 // Unknown mask for bswap.
3810 if (DestByte == ByteValues.size()) return true;
3811
Reid Spencerb83eb642006-10-20 07:07:24 +00003812 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003813 unsigned SrcByte;
3814 if (SI->getOpcode() == Instruction::Shl)
3815 SrcByte = DestByte - ShiftBytes;
3816 else
3817 SrcByte = DestByte + ShiftBytes;
3818
3819 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3820 if (SrcByte != ByteValues.size()-DestByte-1)
3821 return true;
3822
3823 // If the destination byte value is already defined, the values are or'd
3824 // together, which isn't a bswap (unless it's an or of the same bits).
3825 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3826 return true;
3827 ByteValues[DestByte] = SI->getOperand(0);
3828 return false;
3829}
3830
3831/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3832/// If so, insert the new bswap intrinsic and return it.
3833Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003834 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3835 if (!ITy || ITy->getBitWidth() % 16)
3836 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003837
3838 /// ByteValues - For each byte of the result, we keep track of which value
3839 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003840 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003841 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003842
3843 // Try to find all the pieces corresponding to the bswap.
3844 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3845 CollectBSwapParts(I.getOperand(1), ByteValues))
3846 return 0;
3847
3848 // Check to see if all of the bytes come from the same value.
3849 Value *V = ByteValues[0];
3850 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3851
3852 // Check to make sure that all of the bytes come from the same value.
3853 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3854 if (ByteValues[i] != V)
3855 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003856 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003857 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003858 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00003859 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003860}
3861
3862
Chris Lattner7e708292002-06-25 16:13:24 +00003863Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003864 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003865 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003866
Chris Lattner42593e62007-03-24 23:56:43 +00003867 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003868 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003869
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003870 // or X, X = X
3871 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003872 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003873
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003874 // See if we can simplify any instructions used by the instruction whose sole
3875 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003876 if (!isa<VectorType>(I.getType())) {
3877 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3878 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3879 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3880 KnownZero, KnownOne))
3881 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003882 } else if (isa<ConstantAggregateZero>(Op1)) {
3883 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3884 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3885 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3886 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003887 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003888
3889
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003890
Chris Lattner3f5b8772002-05-06 16:14:14 +00003891 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003892 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003893 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003894 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3895 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003896 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003897 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003898 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003899 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003900 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003901 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003902
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003903 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3904 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003905 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003906 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003907 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003908 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003909 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003910 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003911
3912 // Try to fold constant and into select arguments.
3913 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003914 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003915 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003916 if (isa<PHINode>(Op0))
3917 if (Instruction *NV = FoldOpIntoPhi(I))
3918 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003919 }
3920
Chris Lattner4f637d42006-01-06 17:59:59 +00003921 Value *A = 0, *B = 0;
3922 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003923
3924 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3925 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3926 return ReplaceInstUsesWith(I, Op1);
3927 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3928 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3929 return ReplaceInstUsesWith(I, Op0);
3930
Chris Lattner6423d4c2006-07-10 20:25:24 +00003931 // (A | B) | C and A | (B | C) -> bswap if possible.
3932 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003933 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003934 match(Op1, m_Or(m_Value(), m_Value())) ||
3935 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3936 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003937 if (Instruction *BSwap = MatchBSwap(I))
3938 return BSwap;
3939 }
3940
Chris Lattner6e4c6492005-05-09 04:58:36 +00003941 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3942 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003943 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003944 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00003945 InsertNewInstBefore(NOr, I);
3946 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003947 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003948 }
3949
3950 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3951 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003952 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003953 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00003954 InsertNewInstBefore(NOr, I);
3955 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003956 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003957 }
3958
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003959 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00003960 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003961 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3962 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003963 Value *V1 = 0, *V2 = 0, *V3 = 0;
3964 C1 = dyn_cast<ConstantInt>(C);
3965 C2 = dyn_cast<ConstantInt>(D);
3966 if (C1 && C2) { // (A & C1)|(B & C2)
3967 // If we have: ((V + N) & C1) | (V & C2)
3968 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3969 // replace with V+N.
3970 if (C1->getValue() == ~C2->getValue()) {
3971 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3972 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3973 // Add commutes, try both ways.
3974 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3975 return ReplaceInstUsesWith(I, A);
3976 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3977 return ReplaceInstUsesWith(I, A);
3978 }
3979 // Or commutes, try both ways.
3980 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3981 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3982 // Add commutes, try both ways.
3983 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3984 return ReplaceInstUsesWith(I, B);
3985 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3986 return ReplaceInstUsesWith(I, B);
3987 }
3988 }
Chris Lattner044e5332007-04-08 08:01:49 +00003989 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00003990 }
3991
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003992 // Check to see if we have any common things being and'ed. If so, find the
3993 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003994 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3995 if (A == B) // (A & C)|(A & D) == A & (C|D)
3996 V1 = A, V2 = C, V3 = D;
3997 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3998 V1 = A, V2 = B, V3 = C;
3999 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4000 V1 = C, V2 = A, V3 = D;
4001 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4002 V1 = C, V2 = A, V3 = B;
4003
4004 if (V1) {
4005 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004006 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4007 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004008 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004009 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004010 }
Chris Lattnere511b742006-11-14 07:46:50 +00004011
4012 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004013 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4014 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4015 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004016 SI0->getOperand(1) == SI1->getOperand(1) &&
4017 (SI0->hasOneUse() || SI1->hasOneUse())) {
4018 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004019 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004020 SI1->getOperand(0),
4021 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004022 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004023 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004024 }
4025 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004026
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004027 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4028 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004029 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004030 } else {
4031 A = 0;
4032 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004033 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004034 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4035 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004036 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004037
Misha Brukmancb6267b2004-07-30 12:50:08 +00004038 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004039 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004040 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004041 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004042 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004043 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004044 }
Chris Lattnera2881962003-02-18 19:28:33 +00004045
Reid Spencere4d87aa2006-12-23 06:05:41 +00004046 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4047 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4048 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004049 return R;
4050
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004051 Value *LHSVal, *RHSVal;
4052 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004053 ICmpInst::Predicate LHSCC, RHSCC;
4054 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4055 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4056 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4057 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4058 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4059 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4060 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004061 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4062 // We can't fold (ugt x, C) | (sgt x, C2).
4063 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004064 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004065 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004066 bool NeedsSwap;
4067 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004068 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004069 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004070 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004071
4072 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004073 std::swap(LHS, RHS);
4074 std::swap(LHSCst, RHSCst);
4075 std::swap(LHSCC, RHSCC);
4076 }
4077
Reid Spencere4d87aa2006-12-23 06:05:41 +00004078 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004079 // comparing a value against two constants and or'ing the result
4080 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004081 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4082 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004083 // equal.
4084 assert(LHSCst != RHSCst && "Compares not folded above?");
4085
4086 switch (LHSCC) {
4087 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004088 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004089 switch (RHSCC) {
4090 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004091 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004092 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4093 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004094 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004095 LHSVal->getName()+".off");
4096 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004097 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004098 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004099 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004100 break; // (X == 13 | X == 15) -> no change
4101 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4102 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004103 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004104 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4105 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4106 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004107 return ReplaceInstUsesWith(I, RHS);
4108 }
4109 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004110 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004111 switch (RHSCC) {
4112 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004113 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4114 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4115 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004116 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004117 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4118 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4119 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004120 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004121 }
4122 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004123 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004124 switch (RHSCC) {
4125 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004126 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004127 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004128 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004129 // If RHSCst is [us]MAXINT, it is always false. Not handling
4130 // this can cause overflow.
4131 if (RHSCst->isMaxValue(false))
4132 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004133 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4134 false, I);
4135 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4136 break;
4137 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4138 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004139 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004140 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4141 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004142 }
4143 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004144 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004145 switch (RHSCC) {
4146 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004147 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4148 break;
4149 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004150 // If RHSCst is [us]MAXINT, it is always false. Not handling
4151 // this can cause overflow.
4152 if (RHSCst->isMaxValue(true))
4153 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004154 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4155 false, I);
4156 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4157 break;
4158 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4159 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4160 return ReplaceInstUsesWith(I, RHS);
4161 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4162 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004163 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004164 break;
4165 case ICmpInst::ICMP_UGT:
4166 switch (RHSCC) {
4167 default: assert(0 && "Unknown integer condition code!");
4168 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4169 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4170 return ReplaceInstUsesWith(I, LHS);
4171 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4172 break;
4173 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4174 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004175 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004176 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4177 break;
4178 }
4179 break;
4180 case ICmpInst::ICMP_SGT:
4181 switch (RHSCC) {
4182 default: assert(0 && "Unknown integer condition code!");
4183 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4184 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4185 return ReplaceInstUsesWith(I, LHS);
4186 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4187 break;
4188 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4189 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004190 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004191 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4192 break;
4193 }
4194 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004195 }
4196 }
4197 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004198
4199 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004200 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004201 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004202 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004203 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4204 !isa<ICmpInst>(Op1C->getOperand(0))) {
4205 const Type *SrcTy = Op0C->getOperand(0)->getType();
4206 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4207 // Only do this if the casts both really cause code to be
4208 // generated.
4209 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4210 I.getType(), TD) &&
4211 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4212 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004213 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004214 Op1C->getOperand(0),
4215 I.getName());
4216 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004217 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004218 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004219 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004220 }
Chris Lattner99c65742007-10-24 05:38:08 +00004221 }
4222
4223
4224 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4225 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4226 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4227 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004228 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4229 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004230 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4231 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4232 // If either of the constants are nans, then the whole thing returns
4233 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004234 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004235 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4236
4237 // Otherwise, no need to compare the two constants, compare the
4238 // rest.
4239 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4240 RHS->getOperand(0));
4241 }
4242 }
4243 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004244
Chris Lattner7e708292002-06-25 16:13:24 +00004245 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004246}
4247
Dan Gohman844731a2008-05-13 00:00:25 +00004248namespace {
4249
Chris Lattnerc317d392004-02-16 01:20:27 +00004250// XorSelf - Implements: X ^ X --> 0
4251struct XorSelf {
4252 Value *RHS;
4253 XorSelf(Value *rhs) : RHS(rhs) {}
4254 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4255 Instruction *apply(BinaryOperator &Xor) const {
4256 return &Xor;
4257 }
4258};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004259
Dan Gohman844731a2008-05-13 00:00:25 +00004260}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004261
Chris Lattner7e708292002-06-25 16:13:24 +00004262Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004263 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004264 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004265
Evan Chengd34af782008-03-25 20:07:13 +00004266 if (isa<UndefValue>(Op1)) {
4267 if (isa<UndefValue>(Op0))
4268 // Handle undef ^ undef -> 0 special case. This is a common
4269 // idiom (misuse).
4270 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004271 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004272 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004273
Chris Lattnerc317d392004-02-16 01:20:27 +00004274 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4275 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004276 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004277 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004278 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004279
4280 // See if we can simplify any instructions used by the instruction whose sole
4281 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004282 if (!isa<VectorType>(I.getType())) {
4283 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4284 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4285 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4286 KnownZero, KnownOne))
4287 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004288 } else if (isa<ConstantAggregateZero>(Op1)) {
4289 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004290 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004291
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004292 // Is this a ~ operation?
4293 if (Value *NotOp = dyn_castNotVal(&I)) {
4294 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4295 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4296 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4297 if (Op0I->getOpcode() == Instruction::And ||
4298 Op0I->getOpcode() == Instruction::Or) {
4299 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4300 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4301 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004302 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004303 Op0I->getOperand(1)->getName()+".not");
4304 InsertNewInstBefore(NotY, I);
4305 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004306 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004307 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004308 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004309 }
4310 }
4311 }
4312 }
4313
4314
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004315 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004316 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4317 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4318 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004319 return new ICmpInst(ICI->getInversePredicate(),
4320 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004321
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004322 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4323 return new FCmpInst(FCI->getInversePredicate(),
4324 FCI->getOperand(0), FCI->getOperand(1));
4325 }
4326
Nick Lewycky517e1f52008-05-31 19:01:33 +00004327 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4328 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4329 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4330 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4331 Instruction::CastOps Opcode = Op0C->getOpcode();
4332 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4333 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4334 Op0C->getDestTy())) {
4335 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4336 CI->getOpcode(), CI->getInversePredicate(),
4337 CI->getOperand(0), CI->getOperand(1)), I);
4338 NewCI->takeName(CI);
4339 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4340 }
4341 }
4342 }
4343 }
4344 }
4345
Reid Spencere4d87aa2006-12-23 06:05:41 +00004346 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004347 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004348 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4349 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004350 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4351 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004352 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004353 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004354 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004355
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004356 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004357 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004358 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004359 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004360 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004361 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004362 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004363 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004364 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004365 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004366 // (X + C) ^ signbit -> (X + C + signbit)
4367 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004368 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004369
Chris Lattner7c4049c2004-01-12 19:35:11 +00004370 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004371 } else if (Op0I->getOpcode() == Instruction::Or) {
4372 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004373 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004374 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4375 // Anything in both C1 and C2 is known to be zero, remove it from
4376 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004377 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004378 NewRHS = ConstantExpr::getAnd(NewRHS,
4379 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004380 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004381 I.setOperand(0, Op0I->getOperand(0));
4382 I.setOperand(1, NewRHS);
4383 return &I;
4384 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004385 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004386 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004387 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004388
4389 // Try to fold constant and into select arguments.
4390 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004391 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004392 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004393 if (isa<PHINode>(Op0))
4394 if (Instruction *NV = FoldOpIntoPhi(I))
4395 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004396 }
4397
Chris Lattner8d969642003-03-10 23:06:50 +00004398 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004399 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004400 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004401
Chris Lattner8d969642003-03-10 23:06:50 +00004402 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004403 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004404 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004405
Chris Lattner318bf792007-03-18 22:51:34 +00004406
4407 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4408 if (Op1I) {
4409 Value *A, *B;
4410 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4411 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004412 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004413 I.swapOperands();
4414 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004415 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004416 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004417 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004418 }
Chris Lattner318bf792007-03-18 22:51:34 +00004419 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4420 if (Op0 == A) // A^(A^B) == B
4421 return ReplaceInstUsesWith(I, B);
4422 else if (Op0 == B) // A^(B^A) == B
4423 return ReplaceInstUsesWith(I, A);
4424 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004425 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004426 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004427 std::swap(A, B);
4428 }
Chris Lattner318bf792007-03-18 22:51:34 +00004429 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004430 I.swapOperands(); // Simplified below.
4431 std::swap(Op0, Op1);
4432 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004433 }
Chris Lattner318bf792007-03-18 22:51:34 +00004434 }
4435
4436 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4437 if (Op0I) {
4438 Value *A, *B;
4439 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4440 if (A == Op1) // (B|A)^B == (A|B)^B
4441 std::swap(A, B);
4442 if (B == Op1) { // (A|B)^B == A & ~B
4443 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004444 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4445 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004446 }
Chris Lattner318bf792007-03-18 22:51:34 +00004447 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4448 if (Op1 == A) // (A^B)^A == B
4449 return ReplaceInstUsesWith(I, B);
4450 else if (Op1 == B) // (B^A)^A == B
4451 return ReplaceInstUsesWith(I, A);
4452 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4453 if (A == Op1) // (A&B)^A -> (B&A)^A
4454 std::swap(A, B);
4455 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004456 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004457 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004458 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4459 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004460 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004461 }
Chris Lattner318bf792007-03-18 22:51:34 +00004462 }
4463
4464 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4465 if (Op0I && Op1I && Op0I->isShift() &&
4466 Op0I->getOpcode() == Op1I->getOpcode() &&
4467 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4468 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4469 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004470 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004471 Op1I->getOperand(0),
4472 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004473 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004474 Op1I->getOperand(1));
4475 }
4476
4477 if (Op0I && Op1I) {
4478 Value *A, *B, *C, *D;
4479 // (A & B)^(A | B) -> A ^ B
4480 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4481 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4482 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004483 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004484 }
4485 // (A | B)^(A & B) -> A ^ B
4486 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4487 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4488 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004489 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004490 }
4491
4492 // (A & B)^(C & D)
4493 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4494 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4495 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4496 // (X & Y)^(X & Y) -> (Y^Z) & X
4497 Value *X = 0, *Y = 0, *Z = 0;
4498 if (A == C)
4499 X = A, Y = B, Z = D;
4500 else if (A == D)
4501 X = A, Y = B, Z = C;
4502 else if (B == C)
4503 X = B, Y = A, Z = D;
4504 else if (B == D)
4505 X = B, Y = A, Z = C;
4506
4507 if (X) {
4508 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004509 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4510 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004511 }
4512 }
4513 }
4514
Reid Spencere4d87aa2006-12-23 06:05:41 +00004515 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4516 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4517 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004518 return R;
4519
Chris Lattner6fc205f2006-05-05 06:39:07 +00004520 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004521 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004522 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004523 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4524 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004525 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004526 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004527 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4528 I.getType(), TD) &&
4529 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4530 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004531 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004532 Op1C->getOperand(0),
4533 I.getName());
4534 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004535 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004536 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004537 }
Chris Lattner99c65742007-10-24 05:38:08 +00004538 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00004539
Chris Lattner7e708292002-06-25 16:13:24 +00004540 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004541}
4542
Chris Lattnera96879a2004-09-29 17:40:11 +00004543/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4544/// overflowed for this type.
4545static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004546 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004547 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004548
Reid Spencere4e40032007-03-21 23:19:50 +00004549 if (IsSigned)
4550 if (In2->getValue().isNegative())
4551 return Result->getValue().sgt(In1->getValue());
4552 else
4553 return Result->getValue().slt(In1->getValue());
4554 else
4555 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004556}
4557
Chris Lattner574da9b2005-01-13 20:14:25 +00004558/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4559/// code necessary to compute the offset from the base pointer (without adding
4560/// in the base pointer). Return the result as a signed integer of intptr size.
4561static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4562 TargetData &TD = IC.getTargetData();
4563 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004564 const Type *IntPtrTy = TD.getIntPtrType();
4565 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004566
4567 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004568 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004569 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004570
Chris Lattner574da9b2005-01-13 20:14:25 +00004571 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4572 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004573 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004574 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4575 if (OpC->isZero()) continue;
4576
4577 // Handle a struct index, which adds its field offset to the pointer.
4578 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4579 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4580
4581 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4582 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004583 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004584 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004585 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004586 ConstantInt::get(IntPtrTy, Size),
4587 GEP->getName()+".offs"), I);
4588 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004589 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004590
4591 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4592 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4593 Scale = ConstantExpr::getMul(OC, Scale);
4594 if (Constant *RC = dyn_cast<Constant>(Result))
4595 Result = ConstantExpr::getAdd(RC, Scale);
4596 else {
4597 // Emit an add instruction.
4598 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004599 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004600 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004601 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004602 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004603 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004604 // Convert to correct type.
4605 if (Op->getType() != IntPtrTy) {
4606 if (Constant *OpC = dyn_cast<Constant>(Op))
4607 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4608 else
4609 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4610 Op->getName()+".c"), I);
4611 }
4612 if (Size != 1) {
4613 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4614 if (Constant *OpC = dyn_cast<Constant>(Op))
4615 Op = ConstantExpr::getMul(OpC, Scale);
4616 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004617 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004618 GEP->getName()+".idx"), I);
4619 }
4620
4621 // Emit an add instruction.
4622 if (isa<Constant>(Op) && isa<Constant>(Result))
4623 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4624 cast<Constant>(Result));
4625 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004626 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004627 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004628 }
4629 return Result;
4630}
4631
Chris Lattner10c0d912008-04-22 02:53:33 +00004632
4633/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4634/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4635/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4636/// complex, and scales are involved. The above expression would also be legal
4637/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4638/// later form is less amenable to optimization though, and we are allowed to
4639/// generate the first by knowing that pointer arithmetic doesn't overflow.
4640///
4641/// If we can't emit an optimized form for this expression, this returns null.
4642///
4643static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4644 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00004645 TargetData &TD = IC.getTargetData();
4646 gep_type_iterator GTI = gep_type_begin(GEP);
4647
4648 // Check to see if this gep only has a single variable index. If so, and if
4649 // any constant indices are a multiple of its scale, then we can compute this
4650 // in terms of the scale of the variable index. For example, if the GEP
4651 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4652 // because the expression will cross zero at the same point.
4653 unsigned i, e = GEP->getNumOperands();
4654 int64_t Offset = 0;
4655 for (i = 1; i != e; ++i, ++GTI) {
4656 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4657 // Compute the aggregate offset of constant indices.
4658 if (CI->isZero()) continue;
4659
4660 // Handle a struct index, which adds its field offset to the pointer.
4661 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4662 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4663 } else {
4664 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4665 Offset += Size*CI->getSExtValue();
4666 }
4667 } else {
4668 // Found our variable index.
4669 break;
4670 }
4671 }
4672
4673 // If there are no variable indices, we must have a constant offset, just
4674 // evaluate it the general way.
4675 if (i == e) return 0;
4676
4677 Value *VariableIdx = GEP->getOperand(i);
4678 // Determine the scale factor of the variable element. For example, this is
4679 // 4 if the variable index is into an array of i32.
4680 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4681
4682 // Verify that there are no other variable indices. If so, emit the hard way.
4683 for (++i, ++GTI; i != e; ++i, ++GTI) {
4684 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4685 if (!CI) return 0;
4686
4687 // Compute the aggregate offset of constant indices.
4688 if (CI->isZero()) continue;
4689
4690 // Handle a struct index, which adds its field offset to the pointer.
4691 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4692 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4693 } else {
4694 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4695 Offset += Size*CI->getSExtValue();
4696 }
4697 }
4698
4699 // Okay, we know we have a single variable index, which must be a
4700 // pointer/array/vector index. If there is no offset, life is simple, return
4701 // the index.
4702 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4703 if (Offset == 0) {
4704 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4705 // we don't need to bother extending: the extension won't affect where the
4706 // computation crosses zero.
4707 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4708 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4709 VariableIdx->getNameStart(), &I);
4710 return VariableIdx;
4711 }
4712
4713 // Otherwise, there is an index. The computation we will do will be modulo
4714 // the pointer size, so get it.
4715 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4716
4717 Offset &= PtrSizeMask;
4718 VariableScale &= PtrSizeMask;
4719
4720 // To do this transformation, any constant index must be a multiple of the
4721 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4722 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4723 // multiple of the variable scale.
4724 int64_t NewOffs = Offset / (int64_t)VariableScale;
4725 if (Offset != NewOffs*(int64_t)VariableScale)
4726 return 0;
4727
4728 // Okay, we can do this evaluation. Start by converting the index to intptr.
4729 const Type *IntPtrTy = TD.getIntPtrType();
4730 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004731 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00004732 true /*SExt*/,
4733 VariableIdx->getNameStart(), &I);
4734 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004735 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00004736}
4737
4738
Reid Spencere4d87aa2006-12-23 06:05:41 +00004739/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004740/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004741Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4742 ICmpInst::Predicate Cond,
4743 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004744 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004745
Chris Lattner10c0d912008-04-22 02:53:33 +00004746 // Look through bitcasts.
4747 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4748 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004749
Chris Lattner574da9b2005-01-13 20:14:25 +00004750 Value *PtrBase = GEPLHS->getOperand(0);
4751 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004752 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00004753 // This transformation (ignoring the base and scales) is valid because we
4754 // know pointers can't overflow. See if we can output an optimized form.
4755 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4756
4757 // If not, synthesize the offset the hard way.
4758 if (Offset == 0)
4759 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00004760 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4761 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004762 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004763 // If the base pointers are different, but the indices are the same, just
4764 // compare the base pointer.
4765 if (PtrBase != GEPRHS->getOperand(0)) {
4766 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004767 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004768 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004769 if (IndicesTheSame)
4770 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4771 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4772 IndicesTheSame = false;
4773 break;
4774 }
4775
4776 // If all indices are the same, just compare the base pointers.
4777 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004778 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4779 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004780
4781 // Otherwise, the base pointers are different and the indices are
4782 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004783 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004784 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004785
Chris Lattnere9d782b2005-01-13 22:25:21 +00004786 // If one of the GEPs has all zero indices, recurse.
4787 bool AllZeros = true;
4788 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4789 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4790 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4791 AllZeros = false;
4792 break;
4793 }
4794 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004795 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4796 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004797
4798 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004799 AllZeros = true;
4800 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4801 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4802 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4803 AllZeros = false;
4804 break;
4805 }
4806 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004807 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004808
Chris Lattner4401c9c2005-01-14 00:20:05 +00004809 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4810 // If the GEPs only differ by one index, compare it.
4811 unsigned NumDifferences = 0; // Keep track of # differences.
4812 unsigned DiffOperand = 0; // The operand that differs.
4813 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4814 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004815 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4816 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004817 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004818 NumDifferences = 2;
4819 break;
4820 } else {
4821 if (NumDifferences++) break;
4822 DiffOperand = i;
4823 }
4824 }
4825
4826 if (NumDifferences == 0) // SAME GEP?
4827 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004828 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00004829 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00004830
Chris Lattner4401c9c2005-01-14 00:20:05 +00004831 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004832 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4833 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004834 // Make sure we do a signed comparison here.
4835 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004836 }
4837 }
4838
Reid Spencere4d87aa2006-12-23 06:05:41 +00004839 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004840 // the result to fold to a constant!
4841 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4842 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4843 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4844 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4845 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004846 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004847 }
4848 }
4849 return 0;
4850}
4851
Chris Lattnera5406232008-05-19 20:18:56 +00004852/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4853///
4854Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4855 Instruction *LHSI,
4856 Constant *RHSC) {
4857 if (!isa<ConstantFP>(RHSC)) return 0;
4858 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4859
4860 // Get the width of the mantissa. We don't want to hack on conversions that
4861 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00004862 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00004863 if (MantissaWidth == -1) return 0; // Unknown.
4864
4865 // Check to see that the input is converted from an integer type that is small
4866 // enough that preserves all bits. TODO: check here for "known" sign bits.
4867 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4868 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4869
4870 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4871 if (isa<UIToFPInst>(LHSI))
4872 ++InputSize;
4873
4874 // If the conversion would lose info, don't hack on this.
4875 if ((int)InputSize > MantissaWidth)
4876 return 0;
4877
4878 // Otherwise, we can potentially simplify the comparison. We know that it
4879 // will always come through as an integer value and we know the constant is
4880 // not a NAN (it would have been previously simplified).
4881 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4882
4883 ICmpInst::Predicate Pred;
4884 switch (I.getPredicate()) {
4885 default: assert(0 && "Unexpected predicate!");
4886 case FCmpInst::FCMP_UEQ:
4887 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4888 case FCmpInst::FCMP_UGT:
4889 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4890 case FCmpInst::FCMP_UGE:
4891 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4892 case FCmpInst::FCMP_ULT:
4893 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4894 case FCmpInst::FCMP_ULE:
4895 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4896 case FCmpInst::FCMP_UNE:
4897 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4898 case FCmpInst::FCMP_ORD:
4899 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4900 case FCmpInst::FCMP_UNO:
4901 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4902 }
4903
4904 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4905
4906 // Now we know that the APFloat is a normal number, zero or inf.
4907
Chris Lattner85162782008-05-20 03:50:52 +00004908 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00004909 // comparing an i8 to 300.0.
4910 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4911
4912 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4913 // and large values.
4914 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4915 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4916 APFloat::rmNearestTiesToEven);
4917 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004918 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4919 Pred == ICmpInst::ICMP_SLE)
Chris Lattnera5406232008-05-19 20:18:56 +00004920 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4921 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4922 }
4923
4924 // See if the RHS value is < SignedMin.
4925 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4926 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4927 APFloat::rmNearestTiesToEven);
4928 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004929 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4930 Pred == ICmpInst::ICMP_SGE)
Chris Lattnera5406232008-05-19 20:18:56 +00004931 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4932 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4933 }
4934
4935 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4936 // it may still be fractional. See if it is fractional by casting the FP
4937 // value to the integer value and back, checking for equality. Don't do this
4938 // for zero, because -0.0 is not fractional.
4939 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4940 if (!RHS.isZero() &&
4941 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4942 // If we had a comparison against a fractional value, we have to adjust
4943 // the compare predicate and sometimes the value. RHSC is rounded towards
4944 // zero at this point.
4945 switch (Pred) {
4946 default: assert(0 && "Unexpected integer comparison!");
4947 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
4948 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4949 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
4950 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4951 case ICmpInst::ICMP_SLE:
4952 // (float)int <= 4.4 --> int <= 4
4953 // (float)int <= -4.4 --> int < -4
4954 if (RHS.isNegative())
4955 Pred = ICmpInst::ICMP_SLT;
4956 break;
4957 case ICmpInst::ICMP_SLT:
4958 // (float)int < -4.4 --> int < -4
4959 // (float)int < 4.4 --> int <= 4
4960 if (!RHS.isNegative())
4961 Pred = ICmpInst::ICMP_SLE;
4962 break;
4963 case ICmpInst::ICMP_SGT:
4964 // (float)int > 4.4 --> int > 4
4965 // (float)int > -4.4 --> int >= -4
4966 if (RHS.isNegative())
4967 Pred = ICmpInst::ICMP_SGE;
4968 break;
4969 case ICmpInst::ICMP_SGE:
4970 // (float)int >= -4.4 --> int >= -4
4971 // (float)int >= 4.4 --> int > 4
4972 if (!RHS.isNegative())
4973 Pred = ICmpInst::ICMP_SGT;
4974 break;
4975 }
4976 }
4977
4978 // Lower this FP comparison into an appropriate integer version of the
4979 // comparison.
4980 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4981}
4982
Reid Spencere4d87aa2006-12-23 06:05:41 +00004983Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4984 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004985 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004986
Chris Lattner58e97462007-01-14 19:42:17 +00004987 // Fold trivial predicates.
4988 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4989 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4990 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4991 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4992
4993 // Simplify 'fcmp pred X, X'
4994 if (Op0 == Op1) {
4995 switch (I.getPredicate()) {
4996 default: assert(0 && "Unknown predicate!");
4997 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4998 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4999 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5000 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5001 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5002 case FCmpInst::FCMP_OLT: // True if ordered and less than
5003 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5004 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5005
5006 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5007 case FCmpInst::FCMP_ULT: // True if unordered or less than
5008 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5009 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5010 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5011 I.setPredicate(FCmpInst::FCMP_UNO);
5012 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5013 return &I;
5014
5015 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5016 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5017 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5018 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5019 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5020 I.setPredicate(FCmpInst::FCMP_ORD);
5021 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5022 return &I;
5023 }
5024 }
5025
Reid Spencere4d87aa2006-12-23 06:05:41 +00005026 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005027 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005028
Reid Spencere4d87aa2006-12-23 06:05:41 +00005029 // Handle fcmp with constant RHS
5030 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005031 // If the constant is a nan, see if we can fold the comparison based on it.
5032 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5033 if (CFP->getValueAPF().isNaN()) {
5034 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5035 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005036 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5037 "Comparison must be either ordered or unordered!");
5038 // True if unordered.
5039 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005040 }
5041 }
5042
Reid Spencere4d87aa2006-12-23 06:05:41 +00005043 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5044 switch (LHSI->getOpcode()) {
5045 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005046 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5047 // block. If in the same block, we're encouraging jump threading. If
5048 // not, we are just pessimizing the code by making an i1 phi.
5049 if (LHSI->getParent() == I.getParent())
5050 if (Instruction *NV = FoldOpIntoPhi(I))
5051 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005052 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005053 case Instruction::SIToFP:
5054 case Instruction::UIToFP:
5055 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5056 return NV;
5057 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005058 case Instruction::Select:
5059 // If either operand of the select is a constant, we can fold the
5060 // comparison into the select arms, which will cause one to be
5061 // constant folded and the select turned into a bitwise or.
5062 Value *Op1 = 0, *Op2 = 0;
5063 if (LHSI->hasOneUse()) {
5064 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5065 // Fold the known value into the constant operand.
5066 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5067 // Insert a new FCmp of the other select operand.
5068 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5069 LHSI->getOperand(2), RHSC,
5070 I.getName()), I);
5071 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5072 // Fold the known value into the constant operand.
5073 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5074 // Insert a new FCmp of the other select operand.
5075 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5076 LHSI->getOperand(1), RHSC,
5077 I.getName()), I);
5078 }
5079 }
5080
5081 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005082 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005083 break;
5084 }
5085 }
5086
5087 return Changed ? &I : 0;
5088}
5089
5090Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5091 bool Changed = SimplifyCompare(I);
5092 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5093 const Type *Ty = Op0->getType();
5094
5095 // icmp X, X
5096 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005097 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005098 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005099
5100 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005101 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005102
Reid Spencere4d87aa2006-12-23 06:05:41 +00005103 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005104 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005105 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5106 isa<ConstantPointerNull>(Op0)) &&
5107 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005108 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005109 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005110 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005111
Reid Spencere4d87aa2006-12-23 06:05:41 +00005112 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005113 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005114 switch (I.getPredicate()) {
5115 default: assert(0 && "Invalid icmp instruction!");
5116 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005117 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005118 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005119 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005120 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005121 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005122 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005123
Reid Spencere4d87aa2006-12-23 06:05:41 +00005124 case ICmpInst::ICMP_UGT:
5125 case ICmpInst::ICMP_SGT:
5126 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005127 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005128 case ICmpInst::ICMP_ULT:
5129 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005130 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005131 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005132 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005133 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005134 case ICmpInst::ICMP_UGE:
5135 case ICmpInst::ICMP_SGE:
5136 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005137 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005138 case ICmpInst::ICMP_ULE:
5139 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005140 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005141 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005142 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005143 }
5144 }
Chris Lattner8b170942002-08-09 23:47:40 +00005145 }
5146
Chris Lattner2be51ae2004-06-09 04:24:29 +00005147 // See if we are doing a comparison between a constant and an instruction that
5148 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005149 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005150 Value *A, *B;
5151
Chris Lattnerb6566012008-01-05 01:18:20 +00005152 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5153 if (I.isEquality() && CI->isNullValue() &&
5154 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5155 // (icmp cond A B) if cond is equality
5156 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005157 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005158
Reid Spencere4d87aa2006-12-23 06:05:41 +00005159 switch (I.getPredicate()) {
5160 default: break;
5161 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5162 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005163 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005164 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5165 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5166 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5167 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005168 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5169 if (CI->isMinValue(true))
5170 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5171 ConstantInt::getAllOnesValue(Op0->getType()));
5172
Reid Spencere4d87aa2006-12-23 06:05:41 +00005173 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005174
Reid Spencere4d87aa2006-12-23 06:05:41 +00005175 case ICmpInst::ICMP_SLT:
5176 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005177 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005178 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5179 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5180 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5181 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5182 break;
5183
5184 case ICmpInst::ICMP_UGT:
5185 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005186 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005187 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5188 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5189 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5190 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005191
5192 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5193 if (CI->isMaxValue(true))
5194 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5195 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005196 break;
5197
5198 case ICmpInst::ICMP_SGT:
5199 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005200 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005201 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5202 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5203 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5204 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5205 break;
5206
5207 case ICmpInst::ICMP_ULE:
5208 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005209 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005210 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5211 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5212 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5213 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5214 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005215
Reid Spencere4d87aa2006-12-23 06:05:41 +00005216 case ICmpInst::ICMP_SLE:
5217 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005218 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005219 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5220 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5221 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5222 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5223 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005224
Reid Spencere4d87aa2006-12-23 06:05:41 +00005225 case ICmpInst::ICMP_UGE:
5226 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005227 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005228 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5229 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5230 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5231 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5232 break;
5233
5234 case ICmpInst::ICMP_SGE:
5235 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005236 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005237 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5238 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5239 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5240 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5241 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005242 }
5243
Reid Spencere4d87aa2006-12-23 06:05:41 +00005244 // If we still have a icmp le or icmp ge instruction, turn it into the
5245 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005246 // already been handled above, this requires little checking.
5247 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005248 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005249 default: break;
5250 case ICmpInst::ICMP_ULE:
5251 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5252 case ICmpInst::ICMP_SLE:
5253 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5254 case ICmpInst::ICMP_UGE:
5255 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5256 case ICmpInst::ICMP_SGE:
5257 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005258 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005259
5260 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005261 // in the input. If this comparison is a normal comparison, it demands all
5262 // bits, if it is a sign bit comparison, it only demands the sign bit.
5263
5264 bool UnusedBit;
5265 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5266
Reid Spencer0460fb32007-03-22 20:36:03 +00005267 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5268 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005269 if (SimplifyDemandedBits(Op0,
5270 isSignBit ? APInt::getSignBit(BitWidth)
5271 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005272 KnownZero, KnownOne, 0))
5273 return &I;
5274
5275 // Given the known and unknown bits, compute a range that the LHS could be
5276 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005277 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005278 // Compute the Min, Max and RHS values based on the known bits. For the
5279 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005280 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5281 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005282 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005283 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5284 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005285 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005286 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5287 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005288 }
5289 switch (I.getPredicate()) { // LE/GE have been folded already.
5290 default: assert(0 && "Unknown icmp opcode!");
5291 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005292 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005293 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005294 break;
5295 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005296 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005297 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005298 break;
5299 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005300 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005301 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005302 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005303 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005304 break;
5305 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005306 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005307 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005308 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005309 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005310 break;
5311 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005312 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005313 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005314 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005315 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005316 break;
5317 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005318 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005319 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005320 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005321 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005322 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005323 }
5324 }
5325
Reid Spencere4d87aa2006-12-23 06:05:41 +00005326 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005327 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005328 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005329 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005330 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5331 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005332 }
5333
Chris Lattner01deb9d2007-04-03 17:43:25 +00005334 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005335 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5336 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5337 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005338 case Instruction::GetElementPtr:
5339 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005340 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005341 bool isAllZeros = true;
5342 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5343 if (!isa<Constant>(LHSI->getOperand(i)) ||
5344 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5345 isAllZeros = false;
5346 break;
5347 }
5348 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005349 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005350 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5351 }
5352 break;
5353
Chris Lattner6970b662005-04-23 15:31:55 +00005354 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005355 // Only fold icmp into the PHI if the phi and fcmp are in the same
5356 // block. If in the same block, we're encouraging jump threading. If
5357 // not, we are just pessimizing the code by making an i1 phi.
5358 if (LHSI->getParent() == I.getParent())
5359 if (Instruction *NV = FoldOpIntoPhi(I))
5360 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005361 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005362 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005363 // If either operand of the select is a constant, we can fold the
5364 // comparison into the select arms, which will cause one to be
5365 // constant folded and the select turned into a bitwise or.
5366 Value *Op1 = 0, *Op2 = 0;
5367 if (LHSI->hasOneUse()) {
5368 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5369 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005370 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5371 // Insert a new ICmp of the other select operand.
5372 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5373 LHSI->getOperand(2), RHSC,
5374 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005375 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5376 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005377 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5378 // Insert a new ICmp of the other select operand.
5379 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5380 LHSI->getOperand(1), RHSC,
5381 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005382 }
5383 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005384
Chris Lattner6970b662005-04-23 15:31:55 +00005385 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005386 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005387 break;
5388 }
Chris Lattner4802d902007-04-06 18:57:34 +00005389 case Instruction::Malloc:
5390 // If we have (malloc != null), and if the malloc has a single use, we
5391 // can assume it is successful and remove the malloc.
5392 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5393 AddToWorkList(LHSI);
5394 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005395 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005396 }
5397 break;
5398 }
Chris Lattner6970b662005-04-23 15:31:55 +00005399 }
5400
Reid Spencere4d87aa2006-12-23 06:05:41 +00005401 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005402 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005403 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005404 return NI;
5405 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005406 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5407 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005408 return NI;
5409
Reid Spencere4d87aa2006-12-23 06:05:41 +00005410 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005411 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5412 // now.
5413 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5414 if (isa<PointerType>(Op0->getType()) &&
5415 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005416 // We keep moving the cast from the left operand over to the right
5417 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005418 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005419
Chris Lattner57d86372007-01-06 01:45:59 +00005420 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5421 // so eliminate it as well.
5422 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5423 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005424
Chris Lattnerde90b762003-11-03 04:25:02 +00005425 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005426 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005427 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005428 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005429 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005430 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005431 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005432 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005433 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005434 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005435 }
Chris Lattner57d86372007-01-06 01:45:59 +00005436 }
5437
5438 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005439 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005440 // This comes up when you have code like
5441 // int X = A < B;
5442 // if (X) ...
5443 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005444 // with a constant or another cast from the same type.
5445 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005446 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005447 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005448 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005449
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005450 // ~x < ~y --> y < x
5451 { Value *A, *B;
5452 if (match(Op0, m_Not(m_Value(A))) &&
5453 match(Op1, m_Not(m_Value(B))))
5454 return new ICmpInst(I.getPredicate(), B, A);
5455 }
5456
Chris Lattner65b72ba2006-09-18 04:22:48 +00005457 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005458 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005459
5460 // -x == -y --> x == y
5461 if (match(Op0, m_Neg(m_Value(A))) &&
5462 match(Op1, m_Neg(m_Value(B))))
5463 return new ICmpInst(I.getPredicate(), A, B);
5464
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005465 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5466 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5467 Value *OtherVal = A == Op1 ? B : A;
5468 return new ICmpInst(I.getPredicate(), OtherVal,
5469 Constant::getNullValue(A->getType()));
5470 }
5471
5472 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5473 // A^c1 == C^c2 --> A == C^(c1^c2)
5474 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5475 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5476 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005477 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005478 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005479 return new ICmpInst(I.getPredicate(), A,
5480 InsertNewInstBefore(Xor, I));
5481 }
5482
5483 // A^B == A^D -> B == D
5484 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5485 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5486 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5487 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5488 }
5489 }
5490
5491 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5492 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005493 // A == (A^B) -> B == 0
5494 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005495 return new ICmpInst(I.getPredicate(), OtherVal,
5496 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005497 }
5498 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005499 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005500 return new ICmpInst(I.getPredicate(), B,
5501 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005502 }
5503 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005504 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005505 return new ICmpInst(I.getPredicate(), B,
5506 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005507 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005508
Chris Lattner9c2328e2006-11-14 06:06:06 +00005509 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5510 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5511 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5512 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5513 Value *X = 0, *Y = 0, *Z = 0;
5514
5515 if (A == C) {
5516 X = B; Y = D; Z = A;
5517 } else if (A == D) {
5518 X = B; Y = C; Z = A;
5519 } else if (B == C) {
5520 X = A; Y = D; Z = B;
5521 } else if (B == D) {
5522 X = A; Y = C; Z = B;
5523 }
5524
5525 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005526 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5527 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005528 I.setOperand(0, Op1);
5529 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5530 return &I;
5531 }
5532 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005533 }
Chris Lattner7e708292002-06-25 16:13:24 +00005534 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005535}
5536
Chris Lattner562ef782007-06-20 23:46:26 +00005537
5538/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5539/// and CmpRHS are both known to be integer constants.
5540Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5541 ConstantInt *DivRHS) {
5542 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5543 const APInt &CmpRHSV = CmpRHS->getValue();
5544
5545 // FIXME: If the operand types don't match the type of the divide
5546 // then don't attempt this transform. The code below doesn't have the
5547 // logic to deal with a signed divide and an unsigned compare (and
5548 // vice versa). This is because (x /s C1) <s C2 produces different
5549 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5550 // (x /u C1) <u C2. Simply casting the operands and result won't
5551 // work. :( The if statement below tests that condition and bails
5552 // if it finds it.
5553 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5554 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5555 return 0;
5556 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005557 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005558
5559 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5560 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5561 // C2 (CI). By solving for X we can turn this into a range check
5562 // instead of computing a divide.
5563 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5564
5565 // Determine if the product overflows by seeing if the product is
5566 // not equal to the divide. Make sure we do the same kind of divide
5567 // as in the LHS instruction that we're folding.
5568 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5569 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5570
5571 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005572 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005573
Chris Lattner1dbfd482007-06-21 18:11:19 +00005574 // Figure out the interval that is being checked. For example, a comparison
5575 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5576 // Compute this interval based on the constants involved and the signedness of
5577 // the compare/divide. This computes a half-open interval, keeping track of
5578 // whether either value in the interval overflows. After analysis each
5579 // overflow variable is set to 0 if it's corresponding bound variable is valid
5580 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5581 int LoOverflow = 0, HiOverflow = 0;
5582 ConstantInt *LoBound = 0, *HiBound = 0;
5583
5584
Chris Lattner562ef782007-06-20 23:46:26 +00005585 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005586 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005587 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005588 HiOverflow = LoOverflow = ProdOV;
5589 if (!HiOverflow)
5590 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005591 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005592 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005593 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005594 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5595 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005596 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005597 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5598 HiOverflow = LoOverflow = ProdOV;
5599 if (!HiOverflow)
5600 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005601 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005602 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005603 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5604 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005605 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005606 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005607 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005608 }
Dan Gohman76491272008-02-13 22:09:18 +00005609 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005610 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005611 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005612 LoBound = AddOne(DivRHS);
5613 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005614 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5615 HiOverflow = 1; // [INTMIN+1, overflow)
5616 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5617 }
Dan Gohman76491272008-02-13 22:09:18 +00005618 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005619 // e.g. X/-5 op 3 --> [-19, -14)
5620 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005621 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005622 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005623 HiBound = AddOne(Prod);
5624 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005625 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005626 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005627 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005628 HiBound = Subtract(Prod, DivRHS);
5629 }
5630
Chris Lattner1dbfd482007-06-21 18:11:19 +00005631 // Dividing by a negative swaps the condition. LT <-> GT
5632 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005633 }
5634
5635 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005636 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005637 default: assert(0 && "Unhandled icmp opcode!");
5638 case ICmpInst::ICMP_EQ:
5639 if (LoOverflow && HiOverflow)
5640 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5641 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005642 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005643 ICmpInst::ICMP_UGE, X, LoBound);
5644 else if (LoOverflow)
5645 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5646 ICmpInst::ICMP_ULT, X, HiBound);
5647 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005648 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005649 case ICmpInst::ICMP_NE:
5650 if (LoOverflow && HiOverflow)
5651 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5652 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005653 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005654 ICmpInst::ICMP_ULT, X, LoBound);
5655 else if (LoOverflow)
5656 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5657 ICmpInst::ICMP_UGE, X, HiBound);
5658 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005659 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005660 case ICmpInst::ICMP_ULT:
5661 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005662 if (LoOverflow == +1) // Low bound is greater than input range.
5663 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5664 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005665 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005666 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005667 case ICmpInst::ICMP_UGT:
5668 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005669 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005670 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005671 else if (HiOverflow == -1) // High bound less than input range.
5672 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5673 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005674 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5675 else
5676 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5677 }
5678}
5679
5680
Chris Lattner01deb9d2007-04-03 17:43:25 +00005681/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5682///
5683Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5684 Instruction *LHSI,
5685 ConstantInt *RHS) {
5686 const APInt &RHSV = RHS->getValue();
5687
5688 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005689 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005690 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5691 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5692 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005693 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5694 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005695 Value *CompareVal = LHSI->getOperand(0);
5696
5697 // If the sign bit of the XorCST is not set, there is no change to
5698 // the operation, just stop using the Xor.
5699 if (!XorCST->getValue().isNegative()) {
5700 ICI.setOperand(0, CompareVal);
5701 AddToWorkList(LHSI);
5702 return &ICI;
5703 }
5704
5705 // Was the old condition true if the operand is positive?
5706 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5707
5708 // If so, the new one isn't.
5709 isTrueIfPositive ^= true;
5710
5711 if (isTrueIfPositive)
5712 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5713 else
5714 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5715 }
5716 }
5717 break;
5718 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5719 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5720 LHSI->getOperand(0)->hasOneUse()) {
5721 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5722
5723 // If the LHS is an AND of a truncating cast, we can widen the
5724 // and/compare to be the input width without changing the value
5725 // produced, eliminating a cast.
5726 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5727 // We can do this transformation if either the AND constant does not
5728 // have its sign bit set or if it is an equality comparison.
5729 // Extending a relational comparison when we're checking the sign
5730 // bit would not work.
5731 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005732 (ICI.isEquality() ||
5733 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005734 uint32_t BitWidth =
5735 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5736 APInt NewCST = AndCST->getValue();
5737 NewCST.zext(BitWidth);
5738 APInt NewCI = RHSV;
5739 NewCI.zext(BitWidth);
5740 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005741 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00005742 ConstantInt::get(NewCST),LHSI->getName());
5743 InsertNewInstBefore(NewAnd, ICI);
5744 return new ICmpInst(ICI.getPredicate(), NewAnd,
5745 ConstantInt::get(NewCI));
5746 }
5747 }
5748
5749 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5750 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5751 // happens a LOT in code produced by the C front-end, for bitfield
5752 // access.
5753 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5754 if (Shift && !Shift->isShift())
5755 Shift = 0;
5756
5757 ConstantInt *ShAmt;
5758 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5759 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5760 const Type *AndTy = AndCST->getType(); // Type of the and.
5761
5762 // We can fold this as long as we can't shift unknown bits
5763 // into the mask. This can only happen with signed shift
5764 // rights, as they sign-extend.
5765 if (ShAmt) {
5766 bool CanFold = Shift->isLogicalShift();
5767 if (!CanFold) {
5768 // To test for the bad case of the signed shr, see if any
5769 // of the bits shifted in could be tested after the mask.
5770 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5771 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5772
5773 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5774 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5775 AndCST->getValue()) == 0)
5776 CanFold = true;
5777 }
5778
5779 if (CanFold) {
5780 Constant *NewCst;
5781 if (Shift->getOpcode() == Instruction::Shl)
5782 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5783 else
5784 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5785
5786 // Check to see if we are shifting out any of the bits being
5787 // compared.
5788 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5789 // If we shifted bits out, the fold is not going to work out.
5790 // As a special case, check to see if this means that the
5791 // result is always true or false now.
5792 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5793 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5794 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5795 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5796 } else {
5797 ICI.setOperand(1, NewCst);
5798 Constant *NewAndCST;
5799 if (Shift->getOpcode() == Instruction::Shl)
5800 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5801 else
5802 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5803 LHSI->setOperand(1, NewAndCST);
5804 LHSI->setOperand(0, Shift->getOperand(0));
5805 AddToWorkList(Shift); // Shift is dead.
5806 AddUsesToWorkList(ICI);
5807 return &ICI;
5808 }
5809 }
5810 }
5811
5812 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5813 // preferable because it allows the C<<Y expression to be hoisted out
5814 // of a loop if Y is invariant and X is not.
5815 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5816 ICI.isEquality() && !Shift->isArithmeticShift() &&
5817 isa<Instruction>(Shift->getOperand(0))) {
5818 // Compute C << Y.
5819 Value *NS;
5820 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005821 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005822 Shift->getOperand(1), "tmp");
5823 } else {
5824 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005825 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005826 Shift->getOperand(1), "tmp");
5827 }
5828 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5829
5830 // Compute X & (C << Y).
5831 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005832 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00005833 InsertNewInstBefore(NewAnd, ICI);
5834
5835 ICI.setOperand(0, NewAnd);
5836 return &ICI;
5837 }
5838 }
5839 break;
5840
Chris Lattnera0141b92007-07-15 20:42:37 +00005841 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5842 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5843 if (!ShAmt) break;
5844
5845 uint32_t TypeBits = RHSV.getBitWidth();
5846
5847 // Check that the shift amount is in range. If not, don't perform
5848 // undefined shifts. When the shift is visited it will be
5849 // simplified.
5850 if (ShAmt->uge(TypeBits))
5851 break;
5852
5853 if (ICI.isEquality()) {
5854 // If we are comparing against bits always shifted out, the
5855 // comparison cannot succeed.
5856 Constant *Comp =
5857 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5858 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5859 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5860 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5861 return ReplaceInstUsesWith(ICI, Cst);
5862 }
5863
5864 if (LHSI->hasOneUse()) {
5865 // Otherwise strength reduce the shift into an and.
5866 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5867 Constant *Mask =
5868 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005869
Chris Lattnera0141b92007-07-15 20:42:37 +00005870 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005871 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005872 Mask, LHSI->getName()+".mask");
5873 Value *And = InsertNewInstBefore(AndI, ICI);
5874 return new ICmpInst(ICI.getPredicate(), And,
5875 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005876 }
5877 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005878
5879 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5880 bool TrueIfSigned = false;
5881 if (LHSI->hasOneUse() &&
5882 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5883 // (X << 31) <s 0 --> (X&1) != 0
5884 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5885 (TypeBits-ShAmt->getZExtValue()-1));
5886 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005887 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005888 Mask, LHSI->getName()+".mask");
5889 Value *And = InsertNewInstBefore(AndI, ICI);
5890
5891 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5892 And, Constant::getNullValue(And->getType()));
5893 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005894 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005895 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005896
5897 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005898 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005899 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005900 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005901 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005902
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005903 // Check that the shift amount is in range. If not, don't perform
5904 // undefined shifts. When the shift is visited it will be
5905 // simplified.
5906 uint32_t TypeBits = RHSV.getBitWidth();
5907 if (ShAmt->uge(TypeBits))
5908 break;
5909
5910 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005911
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005912 // If we are comparing against bits always shifted out, the
5913 // comparison cannot succeed.
5914 APInt Comp = RHSV << ShAmtVal;
5915 if (LHSI->getOpcode() == Instruction::LShr)
5916 Comp = Comp.lshr(ShAmtVal);
5917 else
5918 Comp = Comp.ashr(ShAmtVal);
5919
5920 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5921 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5922 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5923 return ReplaceInstUsesWith(ICI, Cst);
5924 }
5925
5926 // Otherwise, check to see if the bits shifted out are known to be zero.
5927 // If so, we can compare against the unshifted value:
5928 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00005929 if (LHSI->hasOneUse() &&
5930 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005931 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5932 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5933 ConstantExpr::getShl(RHS, ShAmt));
5934 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005935
Evan Chengf30752c2008-04-23 00:38:06 +00005936 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005937 // Otherwise strength reduce the shift into an and.
5938 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5939 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00005940
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005941 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005942 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005943 Mask, LHSI->getName()+".mask");
5944 Value *And = InsertNewInstBefore(AndI, ICI);
5945 return new ICmpInst(ICI.getPredicate(), And,
5946 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005947 }
5948 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005949 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005950
5951 case Instruction::SDiv:
5952 case Instruction::UDiv:
5953 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5954 // Fold this div into the comparison, producing a range check.
5955 // Determine, based on the divide type, what the range is being
5956 // checked. If there is an overflow on the low or high side, remember
5957 // it, otherwise compute the range [low, hi) bounding the new value.
5958 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005959 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5960 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5961 DivRHS))
5962 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005963 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005964
5965 case Instruction::Add:
5966 // Fold: icmp pred (add, X, C1), C2
5967
5968 if (!ICI.isEquality()) {
5969 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5970 if (!LHSC) break;
5971 const APInt &LHSV = LHSC->getValue();
5972
5973 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5974 .subtract(LHSV);
5975
5976 if (ICI.isSignedPredicate()) {
5977 if (CR.getLower().isSignBit()) {
5978 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5979 ConstantInt::get(CR.getUpper()));
5980 } else if (CR.getUpper().isSignBit()) {
5981 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5982 ConstantInt::get(CR.getLower()));
5983 }
5984 } else {
5985 if (CR.getLower().isMinValue()) {
5986 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5987 ConstantInt::get(CR.getUpper()));
5988 } else if (CR.getUpper().isMinValue()) {
5989 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5990 ConstantInt::get(CR.getLower()));
5991 }
5992 }
5993 }
5994 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005995 }
5996
5997 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5998 if (ICI.isEquality()) {
5999 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6000
6001 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6002 // the second operand is a constant, simplify a bit.
6003 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6004 switch (BO->getOpcode()) {
6005 case Instruction::SRem:
6006 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6007 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6008 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6009 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6010 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006011 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006012 BO->getName());
6013 InsertNewInstBefore(NewRem, ICI);
6014 return new ICmpInst(ICI.getPredicate(), NewRem,
6015 Constant::getNullValue(BO->getType()));
6016 }
6017 }
6018 break;
6019 case Instruction::Add:
6020 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6021 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6022 if (BO->hasOneUse())
6023 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6024 Subtract(RHS, BOp1C));
6025 } else if (RHSV == 0) {
6026 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6027 // efficiently invertible, or if the add has just this one use.
6028 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6029
6030 if (Value *NegVal = dyn_castNegVal(BOp1))
6031 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6032 else if (Value *NegVal = dyn_castNegVal(BOp0))
6033 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6034 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006035 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006036 InsertNewInstBefore(Neg, ICI);
6037 Neg->takeName(BO);
6038 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6039 }
6040 }
6041 break;
6042 case Instruction::Xor:
6043 // For the xor case, we can xor two constants together, eliminating
6044 // the explicit xor.
6045 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6046 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6047 ConstantExpr::getXor(RHS, BOC));
6048
6049 // FALLTHROUGH
6050 case Instruction::Sub:
6051 // Replace (([sub|xor] A, B) != 0) with (A != B)
6052 if (RHSV == 0)
6053 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6054 BO->getOperand(1));
6055 break;
6056
6057 case Instruction::Or:
6058 // If bits are being or'd in that are not present in the constant we
6059 // are comparing against, then the comparison could never succeed!
6060 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6061 Constant *NotCI = ConstantExpr::getNot(RHS);
6062 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6063 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6064 isICMP_NE));
6065 }
6066 break;
6067
6068 case Instruction::And:
6069 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6070 // If bits are being compared against that are and'd out, then the
6071 // comparison can never succeed!
6072 if ((RHSV & ~BOC->getValue()) != 0)
6073 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6074 isICMP_NE));
6075
6076 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6077 if (RHS == BOC && RHSV.isPowerOf2())
6078 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6079 ICmpInst::ICMP_NE, LHSI,
6080 Constant::getNullValue(RHS->getType()));
6081
6082 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006083 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006084 Value *X = BO->getOperand(0);
6085 Constant *Zero = Constant::getNullValue(X->getType());
6086 ICmpInst::Predicate pred = isICMP_NE ?
6087 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6088 return new ICmpInst(pred, X, Zero);
6089 }
6090
6091 // ((X & ~7) == 0) --> X < 8
6092 if (RHSV == 0 && isHighOnes(BOC)) {
6093 Value *X = BO->getOperand(0);
6094 Constant *NegX = ConstantExpr::getNeg(BOC);
6095 ICmpInst::Predicate pred = isICMP_NE ?
6096 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6097 return new ICmpInst(pred, X, NegX);
6098 }
6099 }
6100 default: break;
6101 }
6102 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6103 // Handle icmp {eq|ne} <intrinsic>, intcst.
6104 if (II->getIntrinsicID() == Intrinsic::bswap) {
6105 AddToWorkList(II);
6106 ICI.setOperand(0, II->getOperand(1));
6107 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6108 return &ICI;
6109 }
6110 }
6111 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006112 // If the LHS is a cast from an integral value of the same size,
6113 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006114 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6115 Value *CastOp = Cast->getOperand(0);
6116 const Type *SrcTy = CastOp->getType();
6117 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6118 if (SrcTy->isInteger() &&
6119 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6120 // If this is an unsigned comparison, try to make the comparison use
6121 // smaller constant values.
6122 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6123 // X u< 128 => X s> -1
6124 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6125 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6126 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6127 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6128 // X u> 127 => X s< 0
6129 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6130 Constant::getNullValue(SrcTy));
6131 }
6132 }
6133 }
6134 }
6135 return 0;
6136}
6137
6138/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6139/// We only handle extending casts so far.
6140///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006141Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6142 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006143 Value *LHSCIOp = LHSCI->getOperand(0);
6144 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006145 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006146 Value *RHSCIOp;
6147
Chris Lattner8c756c12007-05-05 22:41:33 +00006148 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6149 // integer type is the same size as the pointer type.
6150 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6151 getTargetData().getPointerSizeInBits() ==
6152 cast<IntegerType>(DestTy)->getBitWidth()) {
6153 Value *RHSOp = 0;
6154 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006155 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006156 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6157 RHSOp = RHSC->getOperand(0);
6158 // If the pointer types don't match, insert a bitcast.
6159 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006160 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006161 }
6162
6163 if (RHSOp)
6164 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6165 }
6166
6167 // The code below only handles extension cast instructions, so far.
6168 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006169 if (LHSCI->getOpcode() != Instruction::ZExt &&
6170 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006171 return 0;
6172
Reid Spencere4d87aa2006-12-23 06:05:41 +00006173 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6174 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006175
Reid Spencere4d87aa2006-12-23 06:05:41 +00006176 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006177 // Not an extension from the same type?
6178 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006179 if (RHSCIOp->getType() != LHSCIOp->getType())
6180 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006181
Nick Lewycky4189a532008-01-28 03:48:02 +00006182 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006183 // and the other is a zext), then we can't handle this.
6184 if (CI->getOpcode() != LHSCI->getOpcode())
6185 return 0;
6186
Nick Lewycky4189a532008-01-28 03:48:02 +00006187 // Deal with equality cases early.
6188 if (ICI.isEquality())
6189 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6190
6191 // A signed comparison of sign extended values simplifies into a
6192 // signed comparison.
6193 if (isSignedCmp && isSignedExt)
6194 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6195
6196 // The other three cases all fold into an unsigned comparison.
6197 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006198 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006199
Reid Spencere4d87aa2006-12-23 06:05:41 +00006200 // If we aren't dealing with a constant on the RHS, exit early
6201 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6202 if (!CI)
6203 return 0;
6204
6205 // Compute the constant that would happen if we truncated to SrcTy then
6206 // reextended to DestTy.
6207 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6208 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6209
6210 // If the re-extended constant didn't change...
6211 if (Res2 == CI) {
6212 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6213 // For example, we might have:
6214 // %A = sext short %X to uint
6215 // %B = icmp ugt uint %A, 1330
6216 // It is incorrect to transform this into
6217 // %B = icmp ugt short %X, 1330
6218 // because %A may have negative value.
6219 //
6220 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6221 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006222 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006223 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6224 else
6225 return 0;
6226 }
6227
6228 // The re-extended constant changed so the constant cannot be represented
6229 // in the shorter type. Consequently, we cannot emit a simple comparison.
6230
6231 // First, handle some easy cases. We know the result cannot be equal at this
6232 // point so handle the ICI.isEquality() cases
6233 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006234 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006235 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006236 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006237
6238 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6239 // should have been folded away previously and not enter in here.
6240 Value *Result;
6241 if (isSignedCmp) {
6242 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006243 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006244 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006245 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006246 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006247 } else {
6248 // We're performing an unsigned comparison.
6249 if (isSignedExt) {
6250 // We're performing an unsigned comp with a sign extended value.
6251 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006252 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006253 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6254 NegOne, ICI.getName()), ICI);
6255 } else {
6256 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006257 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006258 }
6259 }
6260
6261 // Finally, return the value computed.
6262 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6263 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6264 return ReplaceInstUsesWith(ICI, Result);
6265 } else {
6266 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6267 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6268 "ICmp should be folded!");
6269 if (Constant *CI = dyn_cast<Constant>(Result))
6270 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6271 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006272 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006273 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006274}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006275
Reid Spencer832254e2007-02-02 02:16:23 +00006276Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6277 return commonShiftTransforms(I);
6278}
6279
6280Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6281 return commonShiftTransforms(I);
6282}
6283
6284Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006285 if (Instruction *R = commonShiftTransforms(I))
6286 return R;
6287
6288 Value *Op0 = I.getOperand(0);
6289
6290 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6291 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6292 if (CSI->isAllOnesValue())
6293 return ReplaceInstUsesWith(I, CSI);
6294
6295 // See if we can turn a signed shr into an unsigned shr.
6296 if (MaskedValueIsZero(Op0,
6297 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006298 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006299
6300 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006301}
6302
6303Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6304 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006305 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006306
6307 // shl X, 0 == X and shr X, 0 == X
6308 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006309 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006310 Op0 == Constant::getNullValue(Op0->getType()))
6311 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006312
Reid Spencere4d87aa2006-12-23 06:05:41 +00006313 if (isa<UndefValue>(Op0)) {
6314 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006315 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006316 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006317 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6318 }
6319 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006320 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6321 return ReplaceInstUsesWith(I, Op0);
6322 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006323 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006324 }
6325
Chris Lattner2eefe512004-04-09 19:05:30 +00006326 // Try to fold constant and into select arguments.
6327 if (isa<Constant>(Op0))
6328 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006329 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006330 return R;
6331
Reid Spencerb83eb642006-10-20 07:07:24 +00006332 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006333 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6334 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006335 return 0;
6336}
6337
Reid Spencerb83eb642006-10-20 07:07:24 +00006338Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006339 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006340 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006341
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006342 // See if we can simplify any instructions used by the instruction whose sole
6343 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006344 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6345 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6346 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006347 KnownZero, KnownOne))
6348 return &I;
6349
Chris Lattner4d5542c2006-01-06 07:12:35 +00006350 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6351 // of a signed value.
6352 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006353 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006354 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006355 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6356 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006357 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006358 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006359 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006360 }
6361
6362 // ((X*C1) << C2) == (X * (C1 << C2))
6363 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6364 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6365 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006366 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006367 ConstantExpr::getShl(BOOp, Op1));
6368
6369 // Try to fold constant and into select arguments.
6370 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6371 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6372 return R;
6373 if (isa<PHINode>(Op0))
6374 if (Instruction *NV = FoldOpIntoPhi(I))
6375 return NV;
6376
Chris Lattner8999dd32007-12-22 09:07:47 +00006377 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6378 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6379 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6380 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6381 // place. Don't try to do this transformation in this case. Also, we
6382 // require that the input operand is a shift-by-constant so that we have
6383 // confidence that the shifts will get folded together. We could do this
6384 // xform in more cases, but it is unlikely to be profitable.
6385 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6386 isa<ConstantInt>(TrOp->getOperand(1))) {
6387 // Okay, we'll do this xform. Make the shift of shift.
6388 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006389 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006390 I.getName());
6391 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6392
6393 // For logical shifts, the truncation has the effect of making the high
6394 // part of the register be zeros. Emulate this by inserting an AND to
6395 // clear the top bits as needed. This 'and' will usually be zapped by
6396 // other xforms later if dead.
6397 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6398 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6399 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6400
6401 // The mask we constructed says what the trunc would do if occurring
6402 // between the shifts. We want to know the effect *after* the second
6403 // shift. We know that it is a logical shift by a constant, so adjust the
6404 // mask as appropriate.
6405 if (I.getOpcode() == Instruction::Shl)
6406 MaskV <<= Op1->getZExtValue();
6407 else {
6408 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6409 MaskV = MaskV.lshr(Op1->getZExtValue());
6410 }
6411
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006412 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006413 TI->getName());
6414 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6415
6416 // Return the value truncated to the interesting size.
6417 return new TruncInst(And, I.getType());
6418 }
6419 }
6420
Chris Lattner4d5542c2006-01-06 07:12:35 +00006421 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006422 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6423 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6424 Value *V1, *V2;
6425 ConstantInt *CC;
6426 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006427 default: break;
6428 case Instruction::Add:
6429 case Instruction::And:
6430 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006431 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006432 // These operators commute.
6433 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006434 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6435 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006436 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006437 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006438 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006439 Op0BO->getName());
6440 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006441 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006442 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006443 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006444 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006445 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006446 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006447 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006448 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006449
Chris Lattner150f12a2005-09-18 06:30:59 +00006450 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006451 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006452 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006453 match(Op0BOOp1,
6454 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006455 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6456 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006457 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006458 Op0BO->getOperand(0), Op1,
6459 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006460 InsertNewInstBefore(YS, I); // (Y << C)
6461 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006462 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006463 V1->getName()+".mask");
6464 InsertNewInstBefore(XM, I); // X & (CC << C)
6465
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006466 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006467 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006468 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006469
Reid Spencera07cb7d2007-02-02 14:41:37 +00006470 // FALL THROUGH.
6471 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006472 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006473 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6474 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006475 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006476 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006477 Op0BO->getOperand(1), Op1,
6478 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006479 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006480 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006481 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006482 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006483 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006484 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006485 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006486 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006487 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006488
Chris Lattner13d4ab42006-05-31 21:14:00 +00006489 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006490 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6491 match(Op0BO->getOperand(0),
6492 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006493 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006494 cast<BinaryOperator>(Op0BO->getOperand(0))
6495 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006496 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006497 Op0BO->getOperand(1), Op1,
6498 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006499 InsertNewInstBefore(YS, I); // (Y << C)
6500 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006501 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006502 V1->getName()+".mask");
6503 InsertNewInstBefore(XM, I); // X & (CC << C)
6504
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006505 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006506 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006507
Chris Lattner11021cb2005-09-18 05:12:10 +00006508 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006509 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006510 }
6511
6512
6513 // If the operand is an bitwise operator with a constant RHS, and the
6514 // shift is the only use, we can pull it out of the shift.
6515 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6516 bool isValid = true; // Valid only for And, Or, Xor
6517 bool highBitSet = false; // Transform if high bit of constant set?
6518
6519 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006520 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006521 case Instruction::Add:
6522 isValid = isLeftShift;
6523 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006524 case Instruction::Or:
6525 case Instruction::Xor:
6526 highBitSet = false;
6527 break;
6528 case Instruction::And:
6529 highBitSet = true;
6530 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006531 }
6532
6533 // If this is a signed shift right, and the high bit is modified
6534 // by the logical operation, do not perform the transformation.
6535 // The highBitSet boolean indicates the value of the high bit of
6536 // the constant which would cause it to be modified for this
6537 // operation.
6538 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006539 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006540 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006541
6542 if (isValid) {
6543 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6544
6545 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006546 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006547 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006548 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006549
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006550 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006551 NewRHS);
6552 }
6553 }
6554 }
6555 }
6556
Chris Lattnerad0124c2006-01-06 07:52:12 +00006557 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006558 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6559 if (ShiftOp && !ShiftOp->isShift())
6560 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006561
Reid Spencerb83eb642006-10-20 07:07:24 +00006562 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006563 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006564 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6565 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006566 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6567 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6568 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006569
Zhou Sheng4351c642007-04-02 08:20:41 +00006570 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006571 if (AmtSum > TypeBits)
6572 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006573
6574 const IntegerType *Ty = cast<IntegerType>(I.getType());
6575
6576 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006577 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006578 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006579 ConstantInt::get(Ty, AmtSum));
6580 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6581 I.getOpcode() == Instruction::AShr) {
6582 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006583 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006584 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6585 I.getOpcode() == Instruction::LShr) {
6586 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6587 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006588 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006589 InsertNewInstBefore(Shift, I);
6590
Zhou Shenge9e03f62007-03-28 15:02:20 +00006591 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006592 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006593 }
6594
Chris Lattnerb87056f2007-02-05 00:57:54 +00006595 // Okay, if we get here, one shift must be left, and the other shift must be
6596 // right. See if the amounts are equal.
6597 if (ShiftAmt1 == ShiftAmt2) {
6598 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6599 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006600 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006601 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006602 }
6603 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6604 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006605 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006606 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006607 }
6608 // We can simplify ((X << C) >>s C) into a trunc + sext.
6609 // NOTE: we could do this for any C, but that would make 'unusual' integer
6610 // types. For now, just stick to ones well-supported by the code
6611 // generators.
6612 const Type *SExtType = 0;
6613 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006614 case 1 :
6615 case 8 :
6616 case 16 :
6617 case 32 :
6618 case 64 :
6619 case 128:
6620 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6621 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006622 default: break;
6623 }
6624 if (SExtType) {
6625 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6626 InsertNewInstBefore(NewTrunc, I);
6627 return new SExtInst(NewTrunc, Ty);
6628 }
6629 // Otherwise, we can't handle it yet.
6630 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006631 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006632
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006633 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006634 if (I.getOpcode() == Instruction::Shl) {
6635 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6636 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006637 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006638 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006639 InsertNewInstBefore(Shift, I);
6640
Reid Spencer55702aa2007-03-25 21:11:44 +00006641 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006642 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006643 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006644
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006645 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006646 if (I.getOpcode() == Instruction::LShr) {
6647 assert(ShiftOp->getOpcode() == Instruction::Shl);
6648 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006649 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006650 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006651
Reid Spencerd5e30f02007-03-26 17:18:58 +00006652 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006653 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006654 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006655
6656 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6657 } else {
6658 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006659 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006660
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006661 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006662 if (I.getOpcode() == Instruction::Shl) {
6663 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6664 ShiftOp->getOpcode() == Instruction::AShr);
6665 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006666 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006667 ConstantInt::get(Ty, ShiftDiff));
6668 InsertNewInstBefore(Shift, I);
6669
Reid Spencer55702aa2007-03-25 21:11:44 +00006670 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006671 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006672 }
6673
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006674 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006675 if (I.getOpcode() == Instruction::LShr) {
6676 assert(ShiftOp->getOpcode() == Instruction::Shl);
6677 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006678 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006679 InsertNewInstBefore(Shift, I);
6680
Reid Spencer68d27cf2007-03-26 23:45:51 +00006681 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006682 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006683 }
6684
6685 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006686 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006687 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006688 return 0;
6689}
6690
Chris Lattnera1be5662002-05-02 17:06:02 +00006691
Chris Lattnercfd65102005-10-29 04:36:15 +00006692/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6693/// expression. If so, decompose it, returning some value X, such that Val is
6694/// X*Scale+Offset.
6695///
6696static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006697 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006698 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006699 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006700 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006701 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006702 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006703 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6704 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6705 if (I->getOpcode() == Instruction::Shl) {
6706 // This is a value scaled by '1 << the shift amt'.
6707 Scale = 1U << RHS->getZExtValue();
6708 Offset = 0;
6709 return I->getOperand(0);
6710 } else if (I->getOpcode() == Instruction::Mul) {
6711 // This value is scaled by 'RHS'.
6712 Scale = RHS->getZExtValue();
6713 Offset = 0;
6714 return I->getOperand(0);
6715 } else if (I->getOpcode() == Instruction::Add) {
6716 // We have X+C. Check to see if we really have (X*C2)+C1,
6717 // where C1 is divisible by C2.
6718 unsigned SubScale;
6719 Value *SubVal =
6720 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6721 Offset += RHS->getZExtValue();
6722 Scale = SubScale;
6723 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006724 }
6725 }
6726 }
6727
6728 // Otherwise, we can't look past this.
6729 Scale = 1;
6730 Offset = 0;
6731 return Val;
6732}
6733
6734
Chris Lattnerb3f83972005-10-24 06:03:58 +00006735/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6736/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006737Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006738 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006739 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006740
Chris Lattnerb53c2382005-10-24 06:22:12 +00006741 // Remove any uses of AI that are dead.
6742 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006743
Chris Lattnerb53c2382005-10-24 06:22:12 +00006744 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6745 Instruction *User = cast<Instruction>(*UI++);
6746 if (isInstructionTriviallyDead(User)) {
6747 while (UI != E && *UI == User)
6748 ++UI; // If this instruction uses AI more than once, don't break UI.
6749
Chris Lattnerb53c2382005-10-24 06:22:12 +00006750 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006751 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006752 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006753 }
6754 }
6755
Chris Lattnerb3f83972005-10-24 06:03:58 +00006756 // Get the type really allocated and the type casted to.
6757 const Type *AllocElTy = AI.getAllocatedType();
6758 const Type *CastElTy = PTy->getElementType();
6759 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006760
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006761 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6762 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006763 if (CastElTyAlign < AllocElTyAlign) return 0;
6764
Chris Lattner39387a52005-10-24 06:35:18 +00006765 // If the allocation has multiple uses, only promote it if we are strictly
6766 // increasing the alignment of the resultant allocation. If we keep it the
6767 // same, we open the door to infinite loops of various kinds.
6768 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6769
Duncan Sands514ab342007-11-01 20:53:16 +00006770 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6771 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006772 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006773
Chris Lattner455fcc82005-10-29 03:19:53 +00006774 // See if we can satisfy the modulus by pulling a scale out of the array
6775 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006776 unsigned ArraySizeScale;
6777 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006778 Value *NumElements = // See if the array size is a decomposable linear expr.
6779 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6780
Chris Lattner455fcc82005-10-29 03:19:53 +00006781 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6782 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006783 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6784 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006785
Chris Lattner455fcc82005-10-29 03:19:53 +00006786 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6787 Value *Amt = 0;
6788 if (Scale == 1) {
6789 Amt = NumElements;
6790 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006791 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006792 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6793 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006794 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006795 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006796 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006797 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00006798 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006799 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006800 }
6801
Jeff Cohen86796be2007-04-04 16:58:57 +00006802 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6803 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006804 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00006805 Amt = InsertNewInstBefore(Tmp, AI);
6806 }
6807
Chris Lattnerb3f83972005-10-24 06:03:58 +00006808 AllocationInst *New;
6809 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006810 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006811 else
Chris Lattner6934a042007-02-11 01:23:03 +00006812 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006813 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006814 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006815
6816 // If the allocation has multiple uses, insert a cast and change all things
6817 // that used it to use the new cast. This will also hack on CI, but it will
6818 // die soon.
6819 if (!AI.hasOneUse()) {
6820 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006821 // New is the allocation instruction, pointer typed. AI is the original
6822 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6823 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006824 InsertNewInstBefore(NewCast, AI);
6825 AI.replaceAllUsesWith(NewCast);
6826 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006827 return ReplaceInstUsesWith(CI, New);
6828}
6829
Chris Lattner70074e02006-05-13 02:06:03 +00006830/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006831/// and return it as type Ty without inserting any new casts and without
6832/// changing the computed value. This is used by code that tries to decide
6833/// whether promoting or shrinking integer operations to wider or smaller types
6834/// will allow us to eliminate a truncate or extend.
6835///
6836/// This is a truncation operation if Ty is smaller than V->getType(), or an
6837/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00006838bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6839 unsigned CastOpc,
6840 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006841 // We can always evaluate constants in another type.
6842 if (isa<ConstantInt>(V))
6843 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006844
6845 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006846 if (!I) return false;
6847
6848 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006849
Chris Lattner951626b2007-08-02 06:11:14 +00006850 // If this is an extension or truncate, we can often eliminate it.
6851 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6852 // If this is a cast from the destination type, we can trivially eliminate
6853 // it, and this will remove a cast overall.
6854 if (I->getOperand(0)->getType() == Ty) {
6855 // If the first operand is itself a cast, and is eliminable, do not count
6856 // this as an eliminable cast. We would prefer to eliminate those two
6857 // casts first.
6858 if (!isa<CastInst>(I->getOperand(0)))
6859 ++NumCastsRemoved;
6860 return true;
6861 }
6862 }
6863
6864 // We can't extend or shrink something that has multiple uses: doing so would
6865 // require duplicating the instruction in general, which isn't profitable.
6866 if (!I->hasOneUse()) return false;
6867
Chris Lattner70074e02006-05-13 02:06:03 +00006868 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006869 case Instruction::Add:
6870 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006871 case Instruction::And:
6872 case Instruction::Or:
6873 case Instruction::Xor:
6874 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006875 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6876 NumCastsRemoved) &&
6877 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6878 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006879
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006880 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006881 // A multiply can be truncated by truncating its operands.
6882 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6883 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6884 NumCastsRemoved) &&
6885 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6886 NumCastsRemoved);
6887
Chris Lattner46b96052006-11-29 07:18:39 +00006888 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006889 // If we are truncating the result of this SHL, and if it's a shift of a
6890 // constant amount, we can always perform a SHL in a smaller type.
6891 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006892 uint32_t BitWidth = Ty->getBitWidth();
6893 if (BitWidth < OrigTy->getBitWidth() &&
6894 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006895 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6896 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006897 }
6898 break;
6899 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006900 // If this is a truncate of a logical shr, we can truncate it to a smaller
6901 // lshr iff we know that the bits we would otherwise be shifting in are
6902 // already zeros.
6903 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006904 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6905 uint32_t BitWidth = Ty->getBitWidth();
6906 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006907 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006908 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6909 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006910 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6911 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006912 }
6913 }
Chris Lattner46b96052006-11-29 07:18:39 +00006914 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006915 case Instruction::ZExt:
6916 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006917 case Instruction::Trunc:
6918 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006919 // can safely replace it. Note that replacing it does not reduce the number
6920 // of casts in the input.
6921 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006922 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006923
Reid Spencer3da59db2006-11-27 01:05:10 +00006924 break;
6925 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006926 // TODO: Can handle more cases here.
6927 break;
6928 }
6929
6930 return false;
6931}
6932
6933/// EvaluateInDifferentType - Given an expression that
6934/// CanEvaluateInDifferentType returns true for, actually insert the code to
6935/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006936Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006937 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006938 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006939 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006940
6941 // Otherwise, it must be an instruction.
6942 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006943 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006944 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006945 case Instruction::Add:
6946 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006947 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006948 case Instruction::And:
6949 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006950 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006951 case Instruction::AShr:
6952 case Instruction::LShr:
6953 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006954 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006955 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006956 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00006957 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006958 break;
6959 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006960 case Instruction::Trunc:
6961 case Instruction::ZExt:
6962 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006963 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006964 // just return the source. There's no need to insert it because it is not
6965 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006966 if (I->getOperand(0)->getType() == Ty)
6967 return I->getOperand(0);
6968
Chris Lattner951626b2007-08-02 06:11:14 +00006969 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006970 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00006971 Ty, I->getName());
6972 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006973 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006974 // TODO: Can handle more cases here.
6975 assert(0 && "Unreachable!");
6976 break;
6977 }
6978
6979 return InsertNewInstBefore(Res, *I);
6980}
6981
Reid Spencer3da59db2006-11-27 01:05:10 +00006982/// @brief Implement the transforms common to all CastInst visitors.
6983Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006984 Value *Src = CI.getOperand(0);
6985
Dan Gohman23d9d272007-05-11 21:10:54 +00006986 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006987 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006988 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006989 if (Instruction::CastOps opc =
6990 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6991 // The first cast (CSrc) is eliminable so we need to fix up or replace
6992 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006993 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006994 }
6995 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006996
Reid Spencer3da59db2006-11-27 01:05:10 +00006997 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006998 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6999 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7000 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007001
7002 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007003 if (isa<PHINode>(Src))
7004 if (Instruction *NV = FoldOpIntoPhi(CI))
7005 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007006
Reid Spencer3da59db2006-11-27 01:05:10 +00007007 return 0;
7008}
7009
Chris Lattnerd3e28342007-04-27 17:44:50 +00007010/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7011Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7012 Value *Src = CI.getOperand(0);
7013
Chris Lattnerd3e28342007-04-27 17:44:50 +00007014 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007015 // If casting the result of a getelementptr instruction with no offset, turn
7016 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007017 if (GEP->hasAllZeroIndices()) {
7018 // Changing the cast operand is usually not a good idea but it is safe
7019 // here because the pointer operand is being replaced with another
7020 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007021 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007022 CI.setOperand(0, GEP->getOperand(0));
7023 return &CI;
7024 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007025
7026 // If the GEP has a single use, and the base pointer is a bitcast, and the
7027 // GEP computes a constant offset, see if we can convert these three
7028 // instructions into fewer. This typically happens with unions and other
7029 // non-type-safe code.
7030 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7031 if (GEP->hasAllConstantIndices()) {
7032 // We are guaranteed to get a constant from EmitGEPOffset.
7033 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7034 int64_t Offset = OffsetV->getSExtValue();
7035
7036 // Get the base pointer input of the bitcast, and the type it points to.
7037 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7038 const Type *GEPIdxTy =
7039 cast<PointerType>(OrigBase->getType())->getElementType();
7040 if (GEPIdxTy->isSized()) {
7041 SmallVector<Value*, 8> NewIndices;
7042
Chris Lattnerc42e2262007-05-05 01:59:31 +00007043 // Start with the index over the outer type. Note that the type size
7044 // might be zero (even if the offset isn't zero) if the indexed type
7045 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007046 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007047 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007048 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007049 FirstIdx = Offset/TySize;
7050 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007051
Chris Lattnerc42e2262007-05-05 01:59:31 +00007052 // Handle silly modulus not returning values values [0..TySize).
7053 if (Offset < 0) {
7054 --FirstIdx;
7055 Offset += TySize;
7056 assert(Offset >= 0);
7057 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007058 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007059 }
7060
7061 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007062
7063 // Index into the types. If we fail, set OrigBase to null.
7064 while (Offset) {
7065 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7066 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007067 if (Offset < (int64_t)SL->getSizeInBytes()) {
7068 unsigned Elt = SL->getElementContainingOffset(Offset);
7069 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007070
Chris Lattner6b6aef82007-05-15 00:16:00 +00007071 Offset -= SL->getElementOffset(Elt);
7072 GEPIdxTy = STy->getElementType(Elt);
7073 } else {
7074 // Otherwise, we can't index into this, bail out.
7075 Offset = 0;
7076 OrigBase = 0;
7077 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007078 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7079 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007080 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007081 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7082 Offset %= EltSize;
7083 } else {
7084 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7085 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007086 GEPIdxTy = STy->getElementType();
7087 } else {
7088 // Otherwise, we can't index into this, bail out.
7089 Offset = 0;
7090 OrigBase = 0;
7091 }
7092 }
7093 if (OrigBase) {
7094 // If we were able to index down into an element, create the GEP
7095 // and bitcast the result. This eliminates one bitcast, potentially
7096 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007097 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7098 NewIndices.begin(),
7099 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007100 InsertNewInstBefore(NGEP, CI);
7101 NGEP->takeName(GEP);
7102
Chris Lattner9bc14642007-04-28 00:57:34 +00007103 if (isa<BitCastInst>(CI))
7104 return new BitCastInst(NGEP, CI.getType());
7105 assert(isa<PtrToIntInst>(CI));
7106 return new PtrToIntInst(NGEP, CI.getType());
7107 }
7108 }
7109 }
7110 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007111 }
7112
7113 return commonCastTransforms(CI);
7114}
7115
7116
7117
Chris Lattnerc739cd62007-03-03 05:27:34 +00007118/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7119/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007120/// cases.
7121/// @brief Implement the transforms common to CastInst with integer operands
7122Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7123 if (Instruction *Result = commonCastTransforms(CI))
7124 return Result;
7125
7126 Value *Src = CI.getOperand(0);
7127 const Type *SrcTy = Src->getType();
7128 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007129 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7130 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007131
Reid Spencer3da59db2006-11-27 01:05:10 +00007132 // See if we can simplify any instructions used by the LHS whose sole
7133 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007134 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7135 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007136 KnownZero, KnownOne))
7137 return &CI;
7138
7139 // If the source isn't an instruction or has more than one use then we
7140 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007141 Instruction *SrcI = dyn_cast<Instruction>(Src);
7142 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007143 return 0;
7144
Chris Lattnerc739cd62007-03-03 05:27:34 +00007145 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007146 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007147 if (!isa<BitCastInst>(CI) &&
7148 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007149 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007150 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007151 // eliminates the cast, so it is always a win. If this is a zero-extension,
7152 // we need to do an AND to maintain the clear top-part of the computation,
7153 // so we require that the input have eliminated at least one cast. If this
7154 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007155 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007156 bool DoXForm;
7157 switch (CI.getOpcode()) {
7158 default:
7159 // All the others use floating point so we shouldn't actually
7160 // get here because of the check above.
7161 assert(0 && "Unknown cast type");
7162 case Instruction::Trunc:
7163 DoXForm = true;
7164 break;
7165 case Instruction::ZExt:
7166 DoXForm = NumCastsRemoved >= 1;
7167 break;
7168 case Instruction::SExt:
7169 DoXForm = NumCastsRemoved >= 2;
7170 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007171 }
7172
7173 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007174 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7175 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007176 assert(Res->getType() == DestTy);
7177 switch (CI.getOpcode()) {
7178 default: assert(0 && "Unknown cast type!");
7179 case Instruction::Trunc:
7180 case Instruction::BitCast:
7181 // Just replace this cast with the result.
7182 return ReplaceInstUsesWith(CI, Res);
7183 case Instruction::ZExt: {
7184 // We need to emit an AND to clear the high bits.
7185 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007186 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7187 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007188 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007189 }
7190 case Instruction::SExt:
7191 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007192 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007193 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7194 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007195 }
7196 }
7197 }
7198
7199 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7200 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7201
7202 switch (SrcI->getOpcode()) {
7203 case Instruction::Add:
7204 case Instruction::Mul:
7205 case Instruction::And:
7206 case Instruction::Or:
7207 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007208 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007209 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7210 // Don't insert two casts if they cannot be eliminated. We allow
7211 // two casts to be inserted if the sizes are the same. This could
7212 // only be converting signedness, which is a noop.
7213 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007214 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7215 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007216 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007217 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7218 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007219 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007220 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007221 }
7222 }
7223
7224 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7225 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7226 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007227 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007228 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007229 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007230 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007231 }
7232 break;
7233 case Instruction::SDiv:
7234 case Instruction::UDiv:
7235 case Instruction::SRem:
7236 case Instruction::URem:
7237 // If we are just changing the sign, rewrite.
7238 if (DestBitSize == SrcBitSize) {
7239 // Don't insert two casts if they cannot be eliminated. We allow
7240 // two casts to be inserted if the sizes are the same. This could
7241 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007242 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7243 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007244 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7245 Op0, DestTy, SrcI);
7246 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7247 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007248 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007249 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7250 }
7251 }
7252 break;
7253
7254 case Instruction::Shl:
7255 // Allow changing the sign of the source operand. Do not allow
7256 // changing the size of the shift, UNLESS the shift amount is a
7257 // constant. We must not change variable sized shifts to a smaller
7258 // size, because it is undefined to shift more bits out than exist
7259 // in the value.
7260 if (DestBitSize == SrcBitSize ||
7261 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007262 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7263 Instruction::BitCast : Instruction::Trunc);
7264 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007265 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007266 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007267 }
7268 break;
7269 case Instruction::AShr:
7270 // If this is a signed shr, and if all bits shifted in are about to be
7271 // truncated off, turn it into an unsigned shr to allow greater
7272 // simplifications.
7273 if (DestBitSize < SrcBitSize &&
7274 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007275 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007276 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7277 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007278 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007279 }
7280 }
7281 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007282 }
7283 return 0;
7284}
7285
Chris Lattner8a9f5712007-04-11 06:57:46 +00007286Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007287 if (Instruction *Result = commonIntCastTransforms(CI))
7288 return Result;
7289
7290 Value *Src = CI.getOperand(0);
7291 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007292 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7293 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007294
7295 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7296 switch (SrcI->getOpcode()) {
7297 default: break;
7298 case Instruction::LShr:
7299 // We can shrink lshr to something smaller if we know the bits shifted in
7300 // are already zeros.
7301 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007302 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007303
7304 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007305 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007306 Value* SrcIOp0 = SrcI->getOperand(0);
7307 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007308 if (ShAmt >= DestBitWidth) // All zeros.
7309 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7310
7311 // Okay, we can shrink this. Truncate the input, then return a new
7312 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007313 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7314 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7315 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007316 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007317 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007318 } else { // This is a variable shr.
7319
7320 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7321 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7322 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007323 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007324 Value *One = ConstantInt::get(SrcI->getType(), 1);
7325
Reid Spencer832254e2007-02-02 02:16:23 +00007326 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007327 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007328 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007329 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007330 SrcI->getOperand(0),
7331 "tmp"), CI);
7332 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007333 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007334 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007335 }
7336 break;
7337 }
7338 }
7339
7340 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007341}
7342
Evan Chengb98a10e2008-03-24 00:21:34 +00007343/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7344/// in order to eliminate the icmp.
7345Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7346 bool DoXform) {
7347 // If we are just checking for a icmp eq of a single bit and zext'ing it
7348 // to an integer, then shift the bit to the appropriate place and then
7349 // cast to integer to avoid the comparison.
7350 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7351 const APInt &Op1CV = Op1C->getValue();
7352
7353 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7354 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7355 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7356 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7357 if (!DoXform) return ICI;
7358
7359 Value *In = ICI->getOperand(0);
7360 Value *Sh = ConstantInt::get(In->getType(),
7361 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007362 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007363 In->getName()+".lobit"),
7364 CI);
7365 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007366 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007367 false/*ZExt*/, "tmp", &CI);
7368
7369 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7370 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007371 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007372 In->getName()+".not"),
7373 CI);
7374 }
7375
7376 return ReplaceInstUsesWith(CI, In);
7377 }
7378
7379
7380
7381 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7382 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7383 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7384 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7385 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7386 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7387 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7388 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7389 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7390 // This only works for EQ and NE
7391 ICI->isEquality()) {
7392 // If Op1C some other power of two, convert:
7393 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7394 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7395 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7396 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7397
7398 APInt KnownZeroMask(~KnownZero);
7399 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7400 if (!DoXform) return ICI;
7401
7402 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7403 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7404 // (X&4) == 2 --> false
7405 // (X&4) != 2 --> true
7406 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7407 Res = ConstantExpr::getZExt(Res, CI.getType());
7408 return ReplaceInstUsesWith(CI, Res);
7409 }
7410
7411 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7412 Value *In = ICI->getOperand(0);
7413 if (ShiftAmt) {
7414 // Perform a logical shr by shiftamt.
7415 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007416 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007417 ConstantInt::get(In->getType(), ShiftAmt),
7418 In->getName()+".lobit"), CI);
7419 }
7420
7421 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7422 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007423 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007424 InsertNewInstBefore(cast<Instruction>(In), CI);
7425 }
7426
7427 if (CI.getType() == In->getType())
7428 return ReplaceInstUsesWith(CI, In);
7429 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007430 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007431 }
7432 }
7433 }
7434
7435 return 0;
7436}
7437
Chris Lattner8a9f5712007-04-11 06:57:46 +00007438Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007439 // If one of the common conversion will work ..
7440 if (Instruction *Result = commonIntCastTransforms(CI))
7441 return Result;
7442
7443 Value *Src = CI.getOperand(0);
7444
7445 // If this is a cast of a cast
7446 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007447 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7448 // types and if the sizes are just right we can convert this into a logical
7449 // 'and' which will be much cheaper than the pair of casts.
7450 if (isa<TruncInst>(CSrc)) {
7451 // Get the sizes of the types involved
7452 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007453 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7454 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7455 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007456 // If we're actually extending zero bits and the trunc is a no-op
7457 if (MidSize < DstSize && SrcSize == DstSize) {
7458 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007459 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007460 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007461 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007462 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007463 // Unfortunately, if the type changed, we need to cast it back.
7464 if (And->getType() != CI.getType()) {
7465 And->setName(CSrc->getName()+".mask");
7466 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007467 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007468 }
7469 return And;
7470 }
7471 }
7472 }
7473
Evan Chengb98a10e2008-03-24 00:21:34 +00007474 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7475 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007476
Evan Chengb98a10e2008-03-24 00:21:34 +00007477 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7478 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7479 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7480 // of the (zext icmp) will be transformed.
7481 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7482 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7483 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7484 (transformZExtICmp(LHS, CI, false) ||
7485 transformZExtICmp(RHS, CI, false))) {
7486 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7487 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007488 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007489 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007490 }
7491
Reid Spencer3da59db2006-11-27 01:05:10 +00007492 return 0;
7493}
7494
Chris Lattner8a9f5712007-04-11 06:57:46 +00007495Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007496 if (Instruction *I = commonIntCastTransforms(CI))
7497 return I;
7498
Chris Lattner8a9f5712007-04-11 06:57:46 +00007499 Value *Src = CI.getOperand(0);
7500
7501 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7502 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7503 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7504 // If we are just checking for a icmp eq of a single bit and zext'ing it
7505 // to an integer, then shift the bit to the appropriate place and then
7506 // cast to integer to avoid the comparison.
7507 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7508 const APInt &Op1CV = Op1C->getValue();
7509
7510 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7511 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7512 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7513 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7514 Value *In = ICI->getOperand(0);
7515 Value *Sh = ConstantInt::get(In->getType(),
7516 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007517 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007518 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007519 CI);
7520 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007521 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007522 true/*SExt*/, "tmp", &CI);
7523
7524 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007525 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007526 In->getName()+".not"), CI);
7527
7528 return ReplaceInstUsesWith(CI, In);
7529 }
7530 }
7531 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00007532
7533 // See if the value being truncated is already sign extended. If so, just
7534 // eliminate the trunc/sext pair.
7535 if (getOpcode(Src) == Instruction::Trunc) {
7536 Value *Op = cast<User>(Src)->getOperand(0);
7537 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7538 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7539 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7540 unsigned NumSignBits = ComputeNumSignBits(Op);
7541
7542 if (OpBits == DestBits) {
7543 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7544 // bits, it is already ready.
7545 if (NumSignBits > DestBits-MidBits)
7546 return ReplaceInstUsesWith(CI, Op);
7547 } else if (OpBits < DestBits) {
7548 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7549 // bits, just sext from i32.
7550 if (NumSignBits > OpBits-MidBits)
7551 return new SExtInst(Op, CI.getType(), "tmp");
7552 } else {
7553 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7554 // bits, just truncate to i32.
7555 if (NumSignBits > OpBits-MidBits)
7556 return new TruncInst(Op, CI.getType(), "tmp");
7557 }
7558 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00007559
Chris Lattnerba417832007-04-11 06:12:58 +00007560 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007561}
7562
Chris Lattnerb7530652008-01-27 05:29:54 +00007563/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7564/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007565static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007566 APFloat F = CFP->getValueAPF();
7567 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007568 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007569 return 0;
7570}
7571
7572/// LookThroughFPExtensions - If this is an fp extension instruction, look
7573/// through it until we get the source value.
7574static Value *LookThroughFPExtensions(Value *V) {
7575 if (Instruction *I = dyn_cast<Instruction>(V))
7576 if (I->getOpcode() == Instruction::FPExt)
7577 return LookThroughFPExtensions(I->getOperand(0));
7578
7579 // If this value is a constant, return the constant in the smallest FP type
7580 // that can accurately represent it. This allows us to turn
7581 // (float)((double)X+2.0) into x+2.0f.
7582 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7583 if (CFP->getType() == Type::PPC_FP128Ty)
7584 return V; // No constant folding of this.
7585 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007586 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007587 return V;
7588 if (CFP->getType() == Type::DoubleTy)
7589 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007590 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007591 return V;
7592 // Don't try to shrink to various long double types.
7593 }
7594
7595 return V;
7596}
7597
7598Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7599 if (Instruction *I = commonCastTransforms(CI))
7600 return I;
7601
7602 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7603 // smaller than the destination type, we can eliminate the truncate by doing
7604 // the add as the smaller type. This applies to add/sub/mul/div as well as
7605 // many builtins (sqrt, etc).
7606 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7607 if (OpI && OpI->hasOneUse()) {
7608 switch (OpI->getOpcode()) {
7609 default: break;
7610 case Instruction::Add:
7611 case Instruction::Sub:
7612 case Instruction::Mul:
7613 case Instruction::FDiv:
7614 case Instruction::FRem:
7615 const Type *SrcTy = OpI->getType();
7616 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7617 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7618 if (LHSTrunc->getType() != SrcTy &&
7619 RHSTrunc->getType() != SrcTy) {
7620 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7621 // If the source types were both smaller than the destination type of
7622 // the cast, do this xform.
7623 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7624 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7625 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7626 CI.getType(), CI);
7627 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7628 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007629 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007630 }
7631 }
7632 break;
7633 }
7634 }
7635 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007636}
7637
7638Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7639 return commonCastTransforms(CI);
7640}
7641
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007642Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7643 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7644 // mantissa to accurately represent all values of X. For example, do not
7645 // do this with i64->float->i64.
7646 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7647 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7648 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00007649 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007650 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7651
7652 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007653}
7654
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007655Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7656 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7657 // mantissa to accurately represent all values of X. For example, do not
7658 // do this with i64->float->i64.
7659 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7660 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7661 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00007662 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007663 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7664
7665 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007666}
7667
7668Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7669 return commonCastTransforms(CI);
7670}
7671
7672Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7673 return commonCastTransforms(CI);
7674}
7675
7676Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007677 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007678}
7679
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007680Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7681 if (Instruction *I = commonCastTransforms(CI))
7682 return I;
7683
7684 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7685 if (!DestPointee->isSized()) return 0;
7686
7687 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7688 ConstantInt *Cst;
7689 Value *X;
7690 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7691 m_ConstantInt(Cst)))) {
7692 // If the source and destination operands have the same type, see if this
7693 // is a single-index GEP.
7694 if (X->getType() == CI.getType()) {
7695 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007696 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007697
7698 // Convert the constant to intptr type.
7699 APInt Offset = Cst->getValue();
7700 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7701
7702 // If Offset is evenly divisible by Size, we can do this xform.
7703 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7704 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007705 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007706 }
7707 }
7708 // TODO: Could handle other cases, e.g. where add is indexing into field of
7709 // struct etc.
7710 } else if (CI.getOperand(0)->hasOneUse() &&
7711 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7712 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7713 // "inttoptr+GEP" instead of "add+intptr".
7714
7715 // Get the size of the pointee type.
7716 uint64_t Size = TD->getABITypeSize(DestPointee);
7717
7718 // Convert the constant to intptr type.
7719 APInt Offset = Cst->getValue();
7720 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7721
7722 // If Offset is evenly divisible by Size, we can do this xform.
7723 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7724 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7725
7726 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7727 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007728 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007729 }
7730 }
7731 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007732}
7733
Chris Lattnerd3e28342007-04-27 17:44:50 +00007734Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007735 // If the operands are integer typed then apply the integer transforms,
7736 // otherwise just apply the common ones.
7737 Value *Src = CI.getOperand(0);
7738 const Type *SrcTy = Src->getType();
7739 const Type *DestTy = CI.getType();
7740
Chris Lattner42a75512007-01-15 02:27:26 +00007741 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007742 if (Instruction *Result = commonIntCastTransforms(CI))
7743 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007744 } else if (isa<PointerType>(SrcTy)) {
7745 if (Instruction *I = commonPointerCastTransforms(CI))
7746 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007747 } else {
7748 if (Instruction *Result = commonCastTransforms(CI))
7749 return Result;
7750 }
7751
7752
7753 // Get rid of casts from one type to the same type. These are useless and can
7754 // be replaced by the operand.
7755 if (DestTy == Src->getType())
7756 return ReplaceInstUsesWith(CI, Src);
7757
Reid Spencer3da59db2006-11-27 01:05:10 +00007758 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007759 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7760 const Type *DstElTy = DstPTy->getElementType();
7761 const Type *SrcElTy = SrcPTy->getElementType();
7762
Nate Begeman83ad90a2008-03-31 00:22:16 +00007763 // If the address spaces don't match, don't eliminate the bitcast, which is
7764 // required for changing types.
7765 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7766 return 0;
7767
Chris Lattnerd3e28342007-04-27 17:44:50 +00007768 // If we are casting a malloc or alloca to a pointer to a type of the same
7769 // size, rewrite the allocation instruction to allocate the "right" type.
7770 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7771 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7772 return V;
7773
Chris Lattnerd717c182007-05-05 22:32:24 +00007774 // If the source and destination are pointers, and this cast is equivalent
7775 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007776 // This can enhance SROA and other transforms that want type-safe pointers.
7777 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7778 unsigned NumZeros = 0;
7779 while (SrcElTy != DstElTy &&
7780 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7781 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7782 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7783 ++NumZeros;
7784 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007785
Chris Lattnerd3e28342007-04-27 17:44:50 +00007786 // If we found a path from the src to dest, create the getelementptr now.
7787 if (SrcElTy == DstElTy) {
7788 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007789 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7790 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007791 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007792 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007793
Reid Spencer3da59db2006-11-27 01:05:10 +00007794 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7795 if (SVI->hasOneUse()) {
7796 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7797 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007798 if (isa<VectorType>(DestTy) &&
7799 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007800 SVI->getType()->getNumElements()) {
7801 CastInst *Tmp;
7802 // If either of the operands is a cast from CI.getType(), then
7803 // evaluating the shuffle in the casted destination's type will allow
7804 // us to eliminate at least one cast.
7805 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7806 Tmp->getOperand(0)->getType() == DestTy) ||
7807 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7808 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007809 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7810 SVI->getOperand(0), DestTy, &CI);
7811 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7812 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007813 // Return a new shuffle vector. Use the same element ID's, as we
7814 // know the vector types match #elts.
7815 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007816 }
7817 }
7818 }
7819 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007820 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007821}
7822
Chris Lattnere576b912004-04-09 23:46:01 +00007823/// GetSelectFoldableOperands - We want to turn code that looks like this:
7824/// %C = or %A, %B
7825/// %D = select %cond, %C, %A
7826/// into:
7827/// %C = select %cond, %B, 0
7828/// %D = or %A, %C
7829///
7830/// Assuming that the specified instruction is an operand to the select, return
7831/// a bitmask indicating which operands of this instruction are foldable if they
7832/// equal the other incoming value of the select.
7833///
7834static unsigned GetSelectFoldableOperands(Instruction *I) {
7835 switch (I->getOpcode()) {
7836 case Instruction::Add:
7837 case Instruction::Mul:
7838 case Instruction::And:
7839 case Instruction::Or:
7840 case Instruction::Xor:
7841 return 3; // Can fold through either operand.
7842 case Instruction::Sub: // Can only fold on the amount subtracted.
7843 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007844 case Instruction::LShr:
7845 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007846 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007847 default:
7848 return 0; // Cannot fold
7849 }
7850}
7851
7852/// GetSelectFoldableConstant - For the same transformation as the previous
7853/// function, return the identity constant that goes into the select.
7854static Constant *GetSelectFoldableConstant(Instruction *I) {
7855 switch (I->getOpcode()) {
7856 default: assert(0 && "This cannot happen!"); abort();
7857 case Instruction::Add:
7858 case Instruction::Sub:
7859 case Instruction::Or:
7860 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007861 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007862 case Instruction::LShr:
7863 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007864 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007865 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007866 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007867 case Instruction::Mul:
7868 return ConstantInt::get(I->getType(), 1);
7869 }
7870}
7871
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007872/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7873/// have the same opcode and only one use each. Try to simplify this.
7874Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7875 Instruction *FI) {
7876 if (TI->getNumOperands() == 1) {
7877 // If this is a non-volatile load or a cast from the same type,
7878 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007879 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007880 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7881 return 0;
7882 } else {
7883 return 0; // unknown unary op.
7884 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007885
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007886 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00007887 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7888 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007889 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007890 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00007891 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007892 }
7893
Reid Spencer832254e2007-02-02 02:16:23 +00007894 // Only handle binary operators here.
7895 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007896 return 0;
7897
7898 // Figure out if the operations have any operands in common.
7899 Value *MatchOp, *OtherOpT, *OtherOpF;
7900 bool MatchIsOpZero;
7901 if (TI->getOperand(0) == FI->getOperand(0)) {
7902 MatchOp = TI->getOperand(0);
7903 OtherOpT = TI->getOperand(1);
7904 OtherOpF = FI->getOperand(1);
7905 MatchIsOpZero = true;
7906 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7907 MatchOp = TI->getOperand(1);
7908 OtherOpT = TI->getOperand(0);
7909 OtherOpF = FI->getOperand(0);
7910 MatchIsOpZero = false;
7911 } else if (!TI->isCommutative()) {
7912 return 0;
7913 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7914 MatchOp = TI->getOperand(0);
7915 OtherOpT = TI->getOperand(1);
7916 OtherOpF = FI->getOperand(0);
7917 MatchIsOpZero = true;
7918 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7919 MatchOp = TI->getOperand(1);
7920 OtherOpT = TI->getOperand(0);
7921 OtherOpF = FI->getOperand(1);
7922 MatchIsOpZero = true;
7923 } else {
7924 return 0;
7925 }
7926
7927 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00007928 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
7929 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007930 InsertNewInstBefore(NewSI, SI);
7931
7932 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7933 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007934 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007935 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007936 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007937 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007938 assert(0 && "Shouldn't get here");
7939 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007940}
7941
Chris Lattner3d69f462004-03-12 05:52:32 +00007942Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007943 Value *CondVal = SI.getCondition();
7944 Value *TrueVal = SI.getTrueValue();
7945 Value *FalseVal = SI.getFalseValue();
7946
7947 // select true, X, Y -> X
7948 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007949 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007950 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007951
7952 // select C, X, X -> X
7953 if (TrueVal == FalseVal)
7954 return ReplaceInstUsesWith(SI, TrueVal);
7955
Chris Lattnere87597f2004-10-16 18:11:37 +00007956 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7957 return ReplaceInstUsesWith(SI, FalseVal);
7958 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7959 return ReplaceInstUsesWith(SI, TrueVal);
7960 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7961 if (isa<Constant>(TrueVal))
7962 return ReplaceInstUsesWith(SI, TrueVal);
7963 else
7964 return ReplaceInstUsesWith(SI, FalseVal);
7965 }
7966
Reid Spencer4fe16d62007-01-11 18:21:29 +00007967 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007968 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007969 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007970 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007971 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007972 } else {
7973 // Change: A = select B, false, C --> A = and !B, C
7974 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007975 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00007976 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007977 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007978 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007979 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007980 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007981 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007982 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007983 } else {
7984 // Change: A = select B, C, true --> A = or !B, C
7985 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007986 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00007987 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007988 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007989 }
7990 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007991
7992 // select a, b, a -> a&b
7993 // select a, a, b -> a|b
7994 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007995 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00007996 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007997 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007998 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007999
Chris Lattner2eefe512004-04-09 19:05:30 +00008000 // Selecting between two integer constants?
8001 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8002 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008003 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008004 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008005 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008006 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008007 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008008 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008009 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008010 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008011 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008012 }
Chris Lattnerba417832007-04-11 06:12:58 +00008013
8014 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008015
Reid Spencere4d87aa2006-12-23 06:05:41 +00008016 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008017
Reid Spencere4d87aa2006-12-23 06:05:41 +00008018 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008019 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008020 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008021 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008022 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008023 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008024 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008025 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008026 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008027 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008028 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008029 InsertNewInstBefore(SRA, SI);
8030
Reid Spencer3da59db2006-11-27 01:05:10 +00008031 // Finally, convert to the type of the select RHS. We figure out
8032 // if this requires a SExt, Trunc or BitCast based on the sizes.
8033 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008034 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8035 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008036 if (SRASize < SISize)
8037 opc = Instruction::SExt;
8038 else if (SRASize > SISize)
8039 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008040 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008041 }
8042 }
8043
8044
8045 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008046 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008047 // non-constant value, eliminate this whole mess. This corresponds to
8048 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008049 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008050 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008051 cast<Constant>(IC->getOperand(1))->isNullValue())
8052 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8053 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008054 isa<ConstantInt>(ICA->getOperand(1)) &&
8055 (ICA->getOperand(1) == TrueValC ||
8056 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008057 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8058 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008059 // know whether we have a icmp_ne or icmp_eq and whether the
8060 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008061 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008062 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008063 Value *V = ICA;
8064 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008065 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008066 Instruction::Xor, V, ICA->getOperand(1)), SI);
8067 return ReplaceInstUsesWith(SI, V);
8068 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008069 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008070 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008071
8072 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008073 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8074 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008075 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008076 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8077 // This is not safe in general for floating point:
8078 // consider X== -0, Y== +0.
8079 // It becomes safe if either operand is a nonzero constant.
8080 ConstantFP *CFPt, *CFPf;
8081 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8082 !CFPt->getValueAPF().isZero()) ||
8083 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8084 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008085 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008086 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008087 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008088 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008089 return ReplaceInstUsesWith(SI, TrueVal);
8090 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8091
Reid Spencere4d87aa2006-12-23 06:05:41 +00008092 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008093 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008094 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8095 // This is not safe in general for floating point:
8096 // consider X== -0, Y== +0.
8097 // It becomes safe if either operand is a nonzero constant.
8098 ConstantFP *CFPt, *CFPf;
8099 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8100 !CFPt->getValueAPF().isZero()) ||
8101 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8102 !CFPf->getValueAPF().isZero()))
8103 return ReplaceInstUsesWith(SI, FalseVal);
8104 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008105 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008106 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8107 return ReplaceInstUsesWith(SI, TrueVal);
8108 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8109 }
8110 }
8111
8112 // See if we are selecting two values based on a comparison of the two values.
8113 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8114 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8115 // Transform (X == Y) ? X : Y -> Y
8116 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8117 return ReplaceInstUsesWith(SI, FalseVal);
8118 // Transform (X != Y) ? X : Y -> X
8119 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8120 return ReplaceInstUsesWith(SI, TrueVal);
8121 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8122
8123 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8124 // Transform (X == Y) ? Y : X -> X
8125 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8126 return ReplaceInstUsesWith(SI, FalseVal);
8127 // Transform (X != Y) ? Y : X -> Y
8128 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008129 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008130 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8131 }
8132 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008133
Chris Lattner87875da2005-01-13 22:52:24 +00008134 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8135 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8136 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008137 Instruction *AddOp = 0, *SubOp = 0;
8138
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008139 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8140 if (TI->getOpcode() == FI->getOpcode())
8141 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8142 return IV;
8143
8144 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8145 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008146 if (TI->getOpcode() == Instruction::Sub &&
8147 FI->getOpcode() == Instruction::Add) {
8148 AddOp = FI; SubOp = TI;
8149 } else if (FI->getOpcode() == Instruction::Sub &&
8150 TI->getOpcode() == Instruction::Add) {
8151 AddOp = TI; SubOp = FI;
8152 }
8153
8154 if (AddOp) {
8155 Value *OtherAddOp = 0;
8156 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8157 OtherAddOp = AddOp->getOperand(1);
8158 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8159 OtherAddOp = AddOp->getOperand(0);
8160 }
8161
8162 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008163 // So at this point we know we have (Y -> OtherAddOp):
8164 // select C, (add X, Y), (sub X, Z)
8165 Value *NegVal; // Compute -Z
8166 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8167 NegVal = ConstantExpr::getNeg(C);
8168 } else {
8169 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008170 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008171 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008172
8173 Value *NewTrueOp = OtherAddOp;
8174 Value *NewFalseOp = NegVal;
8175 if (AddOp != TI)
8176 std::swap(NewTrueOp, NewFalseOp);
8177 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008178 SelectInst::Create(CondVal, NewTrueOp,
8179 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008180
8181 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008182 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008183 }
8184 }
8185 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008186
Chris Lattnere576b912004-04-09 23:46:01 +00008187 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008188 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008189 // See the comment above GetSelectFoldableOperands for a description of the
8190 // transformation we are doing here.
8191 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8192 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8193 !isa<Constant>(FalseVal))
8194 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8195 unsigned OpToFold = 0;
8196 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8197 OpToFold = 1;
8198 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8199 OpToFold = 2;
8200 }
8201
8202 if (OpToFold) {
8203 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008204 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008205 SelectInst::Create(SI.getCondition(),
8206 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008207 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008208 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008209 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008210 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008211 else {
8212 assert(0 && "Unknown instruction!!");
8213 }
8214 }
8215 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008216
Chris Lattnere576b912004-04-09 23:46:01 +00008217 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8218 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8219 !isa<Constant>(TrueVal))
8220 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8221 unsigned OpToFold = 0;
8222 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8223 OpToFold = 1;
8224 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8225 OpToFold = 2;
8226 }
8227
8228 if (OpToFold) {
8229 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008230 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008231 SelectInst::Create(SI.getCondition(), C,
8232 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008233 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008234 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008235 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008236 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008237 else
Chris Lattnere576b912004-04-09 23:46:01 +00008238 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008239 }
8240 }
8241 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008242
8243 if (BinaryOperator::isNot(CondVal)) {
8244 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8245 SI.setOperand(1, FalseVal);
8246 SI.setOperand(2, TrueVal);
8247 return &SI;
8248 }
8249
Chris Lattner3d69f462004-03-12 05:52:32 +00008250 return 0;
8251}
8252
Dan Gohmaneee962e2008-04-10 18:43:06 +00008253/// EnforceKnownAlignment - If the specified pointer points to an object that
8254/// we control, modify the object's alignment to PrefAlign. This isn't
8255/// often possible though. If alignment is important, a more reliable approach
8256/// is to simply align all global variables and allocation instructions to
8257/// their preferred alignment from the beginning.
8258///
8259static unsigned EnforceKnownAlignment(Value *V,
8260 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008261
Dan Gohmaneee962e2008-04-10 18:43:06 +00008262 User *U = dyn_cast<User>(V);
8263 if (!U) return Align;
8264
8265 switch (getOpcode(U)) {
8266 default: break;
8267 case Instruction::BitCast:
8268 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8269 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008270 // If all indexes are zero, it is just the alignment of the base pointer.
8271 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008272 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8273 if (!isa<Constant>(U->getOperand(i)) ||
8274 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008275 AllZeroOperands = false;
8276 break;
8277 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008278
8279 if (AllZeroOperands) {
8280 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008281 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008282 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008283 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008284 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008285 }
8286
8287 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8288 // If there is a large requested alignment and we can, bump up the alignment
8289 // of the global.
8290 if (!GV->isDeclaration()) {
8291 GV->setAlignment(PrefAlign);
8292 Align = PrefAlign;
8293 }
8294 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8295 // If there is a requested alignment and if this is an alloca, round up. We
8296 // don't do this for malloc, because some systems can't respect the request.
8297 if (isa<AllocaInst>(AI)) {
8298 AI->setAlignment(PrefAlign);
8299 Align = PrefAlign;
8300 }
8301 }
8302
8303 return Align;
8304}
8305
8306/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8307/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8308/// and it is more than the alignment of the ultimate object, see if we can
8309/// increase the alignment of the ultimate object, making this check succeed.
8310unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8311 unsigned PrefAlign) {
8312 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8313 sizeof(PrefAlign) * CHAR_BIT;
8314 APInt Mask = APInt::getAllOnesValue(BitWidth);
8315 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8316 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8317 unsigned TrailZ = KnownZero.countTrailingOnes();
8318 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8319
8320 if (PrefAlign > Align)
8321 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8322
8323 // We don't need to make any adjustment.
8324 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008325}
8326
Chris Lattnerf497b022008-01-13 23:50:23 +00008327Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008328 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8329 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008330 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8331 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8332
8333 if (CopyAlign < MinAlign) {
8334 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8335 return MI;
8336 }
8337
8338 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8339 // load/store.
8340 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8341 if (MemOpLength == 0) return 0;
8342
Chris Lattner37ac6082008-01-14 00:28:35 +00008343 // Source and destination pointer types are always "i8*" for intrinsic. See
8344 // if the size is something we can handle with a single primitive load/store.
8345 // A single load+store correctly handles overlapping memory in the memmove
8346 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008347 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008348 if (Size == 0) return MI; // Delete this mem transfer.
8349
8350 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008351 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008352
Chris Lattner37ac6082008-01-14 00:28:35 +00008353 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008354 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008355
8356 // Memcpy forces the use of i8* for the source and destination. That means
8357 // that if you're using memcpy to move one double around, you'll get a cast
8358 // from double* to i8*. We'd much rather use a double load+store rather than
8359 // an i64 load+store, here because this improves the odds that the source or
8360 // dest address will be promotable. See if we can find a better type than the
8361 // integer datatype.
8362 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8363 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8364 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8365 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8366 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00008367 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00008368 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8369 if (STy->getNumElements() == 1)
8370 SrcETy = STy->getElementType(0);
8371 else
8372 break;
8373 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8374 if (ATy->getNumElements() == 1)
8375 SrcETy = ATy->getElementType();
8376 else
8377 break;
8378 } else
8379 break;
8380 }
8381
Dan Gohman8f8e2692008-05-23 01:52:21 +00008382 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00008383 NewPtrTy = PointerType::getUnqual(SrcETy);
8384 }
8385 }
8386
8387
Chris Lattnerf497b022008-01-13 23:50:23 +00008388 // If the memcpy/memmove provides better alignment info than we can
8389 // infer, use it.
8390 SrcAlign = std::max(SrcAlign, CopyAlign);
8391 DstAlign = std::max(DstAlign, CopyAlign);
8392
8393 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8394 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008395 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8396 InsertNewInstBefore(L, *MI);
8397 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8398
8399 // Set the size of the copy to 0, it will be deleted on the next iteration.
8400 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8401 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008402}
Chris Lattner3d69f462004-03-12 05:52:32 +00008403
Chris Lattner69ea9d22008-04-30 06:39:11 +00008404Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8405 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8406 if (MI->getAlignment()->getZExtValue() < Alignment) {
8407 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8408 return MI;
8409 }
8410
8411 // Extract the length and alignment and fill if they are constant.
8412 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8413 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8414 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8415 return 0;
8416 uint64_t Len = LenC->getZExtValue();
8417 Alignment = MI->getAlignment()->getZExtValue();
8418
8419 // If the length is zero, this is a no-op
8420 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8421
8422 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8423 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8424 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8425
8426 Value *Dest = MI->getDest();
8427 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8428
8429 // Alignment 0 is identity for alignment 1 for memset, but not store.
8430 if (Alignment == 0) Alignment = 1;
8431
8432 // Extract the fill value and store.
8433 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8434 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8435 Alignment), *MI);
8436
8437 // Set the size of the copy to 0, it will be deleted on the next iteration.
8438 MI->setLength(Constant::getNullValue(LenC->getType()));
8439 return MI;
8440 }
8441
8442 return 0;
8443}
8444
8445
Chris Lattner8b0ea312006-01-13 20:11:04 +00008446/// visitCallInst - CallInst simplification. This mostly only handles folding
8447/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8448/// the heavy lifting.
8449///
Chris Lattner9fe38862003-06-19 17:00:31 +00008450Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008451 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8452 if (!II) return visitCallSite(&CI);
8453
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008454 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8455 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008456 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008457 bool Changed = false;
8458
8459 // memmove/cpy/set of zero bytes is a noop.
8460 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8461 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8462
Chris Lattner35b9e482004-10-12 04:52:52 +00008463 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008464 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008465 // Replace the instruction with just byte operations. We would
8466 // transform other cases to loads/stores, but we don't know if
8467 // alignment is sufficient.
8468 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008469 }
8470
Chris Lattner35b9e482004-10-12 04:52:52 +00008471 // If we have a memmove and the source operation is a constant global,
8472 // then the source and dest pointers can't alias, so we can change this
8473 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008474 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008475 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8476 if (GVSrc->isConstant()) {
8477 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008478 Intrinsic::ID MemCpyID;
8479 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8480 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008481 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008482 MemCpyID = Intrinsic::memcpy_i64;
8483 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008484 Changed = true;
8485 }
Chris Lattnera935db82008-05-28 05:30:41 +00008486
8487 // memmove(x,x,size) -> noop.
8488 if (MMI->getSource() == MMI->getDest())
8489 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00008490 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008491
Chris Lattner95a959d2006-03-06 20:18:44 +00008492 // If we can determine a pointer alignment that is bigger than currently
8493 // set, update the alignment.
8494 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008495 if (Instruction *I = SimplifyMemTransfer(MI))
8496 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008497 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8498 if (Instruction *I = SimplifyMemSet(MSI))
8499 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008500 }
8501
Chris Lattner8b0ea312006-01-13 20:11:04 +00008502 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008503 } else {
8504 switch (II->getIntrinsicID()) {
8505 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008506 case Intrinsic::ppc_altivec_lvx:
8507 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008508 case Intrinsic::x86_sse_loadu_ps:
8509 case Intrinsic::x86_sse2_loadu_pd:
8510 case Intrinsic::x86_sse2_loadu_dq:
8511 // Turn PPC lvx -> load if the pointer is known aligned.
8512 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008513 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008514 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8515 PointerType::getUnqual(II->getType()),
8516 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008517 return new LoadInst(Ptr);
8518 }
8519 break;
8520 case Intrinsic::ppc_altivec_stvx:
8521 case Intrinsic::ppc_altivec_stvxl:
8522 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008523 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008524 const Type *OpPtrTy =
8525 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008526 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008527 return new StoreInst(II->getOperand(1), Ptr);
8528 }
8529 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008530 case Intrinsic::x86_sse_storeu_ps:
8531 case Intrinsic::x86_sse2_storeu_pd:
8532 case Intrinsic::x86_sse2_storeu_dq:
8533 case Intrinsic::x86_sse2_storel_dq:
8534 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008535 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008536 const Type *OpPtrTy =
8537 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008538 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008539 return new StoreInst(II->getOperand(2), Ptr);
8540 }
8541 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008542
8543 case Intrinsic::x86_sse_cvttss2si: {
8544 // These intrinsics only demands the 0th element of its input vector. If
8545 // we can simplify the input based on that, do so now.
8546 uint64_t UndefElts;
8547 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8548 UndefElts)) {
8549 II->setOperand(1, V);
8550 return II;
8551 }
8552 break;
8553 }
8554
Chris Lattnere2ed0572006-04-06 19:19:17 +00008555 case Intrinsic::ppc_altivec_vperm:
8556 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008557 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008558 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8559
8560 // Check that all of the elements are integer constants or undefs.
8561 bool AllEltsOk = true;
8562 for (unsigned i = 0; i != 16; ++i) {
8563 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8564 !isa<UndefValue>(Mask->getOperand(i))) {
8565 AllEltsOk = false;
8566 break;
8567 }
8568 }
8569
8570 if (AllEltsOk) {
8571 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008572 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8573 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008574 Value *Result = UndefValue::get(Op0->getType());
8575
8576 // Only extract each element once.
8577 Value *ExtractedElts[32];
8578 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8579
8580 for (unsigned i = 0; i != 16; ++i) {
8581 if (isa<UndefValue>(Mask->getOperand(i)))
8582 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008583 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008584 Idx &= 31; // Match the hardware behavior.
8585
8586 if (ExtractedElts[Idx] == 0) {
8587 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008588 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008589 InsertNewInstBefore(Elt, CI);
8590 ExtractedElts[Idx] = Elt;
8591 }
8592
8593 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008594 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8595 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008596 InsertNewInstBefore(cast<Instruction>(Result), CI);
8597 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008598 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008599 }
8600 }
8601 break;
8602
Chris Lattnera728ddc2006-01-13 21:28:09 +00008603 case Intrinsic::stackrestore: {
8604 // If the save is right next to the restore, remove the restore. This can
8605 // happen when variable allocas are DCE'd.
8606 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8607 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8608 BasicBlock::iterator BI = SS;
8609 if (&*++BI == II)
8610 return EraseInstFromFunction(CI);
8611 }
8612 }
8613
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008614 // Scan down this block to see if there is another stack restore in the
8615 // same block without an intervening call/alloca.
8616 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008617 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008618 bool CannotRemove = false;
8619 for (++BI; &*BI != TI; ++BI) {
8620 if (isa<AllocaInst>(BI)) {
8621 CannotRemove = true;
8622 break;
8623 }
8624 if (isa<CallInst>(BI)) {
8625 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008626 CannotRemove = true;
8627 break;
8628 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008629 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008630 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008631 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008632 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008633
8634 // If the stack restore is in a return/unwind block and if there are no
8635 // allocas or calls between the restore and the return, nuke the restore.
8636 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8637 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008638 break;
8639 }
8640 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008641 }
8642
Chris Lattner8b0ea312006-01-13 20:11:04 +00008643 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008644}
8645
8646// InvokeInst simplification
8647//
8648Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008649 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008650}
8651
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008652/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8653/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008654static bool isSafeToEliminateVarargsCast(const CallSite CS,
8655 const CastInst * const CI,
8656 const TargetData * const TD,
8657 const int ix) {
8658 if (!CI->isLosslessCast())
8659 return false;
8660
8661 // The size of ByVal arguments is derived from the type, so we
8662 // can't change to a type with a different size. If the size were
8663 // passed explicitly we could avoid this check.
8664 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8665 return true;
8666
8667 const Type* SrcTy =
8668 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8669 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8670 if (!SrcTy->isSized() || !DstTy->isSized())
8671 return false;
8672 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8673 return false;
8674 return true;
8675}
8676
Chris Lattnera44d8a22003-10-07 22:32:43 +00008677// visitCallSite - Improvements for call and invoke instructions.
8678//
8679Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008680 bool Changed = false;
8681
8682 // If the callee is a constexpr cast of a function, attempt to move the cast
8683 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008684 if (transformConstExprCastCall(CS)) return 0;
8685
Chris Lattner6c266db2003-10-07 22:54:13 +00008686 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008687
Chris Lattner08b22ec2005-05-13 07:09:09 +00008688 if (Function *CalleeF = dyn_cast<Function>(Callee))
8689 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8690 Instruction *OldCall = CS.getInstruction();
8691 // If the call and callee calling conventions don't match, this call must
8692 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008693 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008694 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8695 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008696 if (!OldCall->use_empty())
8697 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8698 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8699 return EraseInstFromFunction(*OldCall);
8700 return 0;
8701 }
8702
Chris Lattner17be6352004-10-18 02:59:09 +00008703 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8704 // This instruction is not reachable, just remove it. We insert a store to
8705 // undef so that we know that this code is not reachable, despite the fact
8706 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008707 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008708 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008709 CS.getInstruction());
8710
8711 if (!CS.getInstruction()->use_empty())
8712 CS.getInstruction()->
8713 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8714
8715 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8716 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008717 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8718 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008719 }
Chris Lattner17be6352004-10-18 02:59:09 +00008720 return EraseInstFromFunction(*CS.getInstruction());
8721 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008722
Duncan Sandscdb6d922007-09-17 10:26:40 +00008723 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8724 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8725 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8726 return transformCallThroughTrampoline(CS);
8727
Chris Lattner6c266db2003-10-07 22:54:13 +00008728 const PointerType *PTy = cast<PointerType>(Callee->getType());
8729 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8730 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00008731 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00008732 // See if we can optimize any arguments passed through the varargs area of
8733 // the call.
8734 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00008735 E = CS.arg_end(); I != E; ++I, ++ix) {
8736 CastInst *CI = dyn_cast<CastInst>(*I);
8737 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8738 *I = CI->getOperand(0);
8739 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00008740 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00008741 }
Chris Lattner6c266db2003-10-07 22:54:13 +00008742 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008743
Duncan Sandsf0c33542007-12-19 21:13:37 +00008744 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008745 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008746 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008747 Changed = true;
8748 }
8749
Chris Lattner6c266db2003-10-07 22:54:13 +00008750 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008751}
8752
Chris Lattner9fe38862003-06-19 17:00:31 +00008753// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8754// attempt to move the cast to the arguments of the call/invoke.
8755//
8756bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8757 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8758 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008759 if (CE->getOpcode() != Instruction::BitCast ||
8760 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008761 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008762 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008763 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008764 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008765
8766 // Okay, this is a cast from a function to a different type. Unless doing so
8767 // would cause a type conversion of one of our arguments, change this call to
8768 // be a direct call with arguments casted to the appropriate types.
8769 //
8770 const FunctionType *FT = Callee->getFunctionType();
8771 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008772 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00008773
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008774 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00008775 return false; // TODO: Handle multiple return values.
8776
Chris Lattnerf78616b2004-01-14 06:06:08 +00008777 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008778 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00008779 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008780 // Conversion is ok if changing from one pointer type to another or from
8781 // a pointer to an integer of the same size.
8782 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8783 isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType()))
Chris Lattnerec479922007-01-06 02:09:32 +00008784 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008785
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008786 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008787 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008788 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008789 return false; // Cannot transform this return value.
8790
Chris Lattner58d74912008-03-12 17:45:29 +00008791 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8792 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008793 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00008794 return false; // Attribute not compatible with transformed value.
8795 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008796
Chris Lattnerf78616b2004-01-14 06:06:08 +00008797 // If the callsite is an invoke instruction, and the return value is used by
8798 // a PHI node in a successor, we cannot change the return type of the call
8799 // because there is no place to put the cast instruction (without breaking
8800 // the critical edge). Bail out in this case.
8801 if (!Caller->use_empty())
8802 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8803 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8804 UI != E; ++UI)
8805 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8806 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008807 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008808 return false;
8809 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008810
8811 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8812 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008813
Chris Lattner9fe38862003-06-19 17:00:31 +00008814 CallSite::arg_iterator AI = CS.arg_begin();
8815 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8816 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008817 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008818
8819 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008820 return false; // Cannot transform this parameter value.
8821
Chris Lattner58d74912008-03-12 17:45:29 +00008822 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8823 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008824
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008825 // Converting from one pointer type to another or between a pointer and an
8826 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00008827 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008828 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8829 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00008830 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008831 }
8832
8833 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008834 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008835 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008836
Chris Lattner58d74912008-03-12 17:45:29 +00008837 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8838 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008839 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008840 // won't be dropping them. Check that these extra arguments have attributes
8841 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008842 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8843 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008844 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008845 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008846 if (PAttrs & ParamAttr::VarArgsIncompatible)
8847 return false;
8848 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008849
Chris Lattner9fe38862003-06-19 17:00:31 +00008850 // Okay, we decided that this is a safe thing to do: go ahead and start
8851 // inserting cast instructions as necessary...
8852 std::vector<Value*> Args;
8853 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008854 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008855 attrVec.reserve(NumCommonArgs);
8856
8857 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008858 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008859
8860 // If the return value is not being used, the type may not be compatible
8861 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008862 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008863
8864 // Add the new return attributes.
8865 if (RAttrs)
8866 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008867
8868 AI = CS.arg_begin();
8869 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8870 const Type *ParamTy = FT->getParamType(i);
8871 if ((*AI)->getType() == ParamTy) {
8872 Args.push_back(*AI);
8873 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008874 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008875 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008876 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008877 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008878 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008879
8880 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008881 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008882 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008883 }
8884
8885 // If the function takes more arguments than the call was taking, add them
8886 // now...
8887 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8888 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8889
8890 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008891 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008892 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008893 cerr << "WARNING: While resolving call to function '"
8894 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008895 } else {
8896 // Add all of the arguments in their promoted form to the arg list...
8897 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8898 const Type *PTy = getPromotedType((*AI)->getType());
8899 if (PTy != (*AI)->getType()) {
8900 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008901 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8902 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008903 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008904 InsertNewInstBefore(Cast, *Caller);
8905 Args.push_back(Cast);
8906 } else {
8907 Args.push_back(*AI);
8908 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008909
Duncan Sandse1e520f2008-01-13 08:02:44 +00008910 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008911 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00008912 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8913 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008914 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008915 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008916
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008917 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008918 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008919
Chris Lattner58d74912008-03-12 17:45:29 +00008920 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008921
Chris Lattner9fe38862003-06-19 17:00:31 +00008922 Instruction *NC;
8923 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00008924 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008925 Args.begin(), Args.end(),
8926 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008927 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008928 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008929 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00008930 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
8931 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008932 CallInst *CI = cast<CallInst>(Caller);
8933 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008934 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008935 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008936 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008937 }
8938
Chris Lattner6934a042007-02-11 01:23:03 +00008939 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008940 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008941 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008942 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008943 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008944 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008945 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008946
8947 // If this is an invoke instruction, we should insert it after the first
8948 // non-phi, instruction in the normal successor block.
8949 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00008950 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00008951 InsertNewInstBefore(NC, *I);
8952 } else {
8953 // Otherwise, it's a call, just insert cast right after the call instr
8954 InsertNewInstBefore(NC, *Caller);
8955 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008956 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008957 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008958 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008959 }
8960 }
8961
8962 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8963 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008964 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008965 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008966 return true;
8967}
8968
Duncan Sandscdb6d922007-09-17 10:26:40 +00008969// transformCallThroughTrampoline - Turn a call to a function created by the
8970// init_trampoline intrinsic into a direct call to the underlying function.
8971//
8972Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8973 Value *Callee = CS.getCalledValue();
8974 const PointerType *PTy = cast<PointerType>(Callee->getType());
8975 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00008976 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008977
8978 // If the call already has the 'nest' attribute somewhere then give up -
8979 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00008980 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008981 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008982
8983 IntrinsicInst *Tramp =
8984 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8985
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00008986 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00008987 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8988 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8989
Chris Lattner58d74912008-03-12 17:45:29 +00008990 const PAListPtr &NestAttrs = NestF->getParamAttrs();
8991 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008992 unsigned NestIdx = 1;
8993 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008994 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008995
8996 // Look for a parameter marked with the 'nest' attribute.
8997 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8998 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00008999 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009000 // Record the parameter type and any other attributes.
9001 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009002 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009003 break;
9004 }
9005
9006 if (NestTy) {
9007 Instruction *Caller = CS.getInstruction();
9008 std::vector<Value*> NewArgs;
9009 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9010
Chris Lattner58d74912008-03-12 17:45:29 +00009011 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9012 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009013
Duncan Sandscdb6d922007-09-17 10:26:40 +00009014 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009015 // mean appending it. Likewise for attributes.
9016
9017 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009018 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9019 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009020
Duncan Sandscdb6d922007-09-17 10:26:40 +00009021 {
9022 unsigned Idx = 1;
9023 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9024 do {
9025 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009026 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009027 Value *NestVal = Tramp->getOperand(3);
9028 if (NestVal->getType() != NestTy)
9029 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9030 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009031 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009032 }
9033
9034 if (I == E)
9035 break;
9036
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009037 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009038 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009039 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009040 NewAttrs.push_back
9041 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009042
9043 ++Idx, ++I;
9044 } while (1);
9045 }
9046
9047 // The trampoline may have been bitcast to a bogus type (FTy).
9048 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009049 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009050
Duncan Sandscdb6d922007-09-17 10:26:40 +00009051 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009052 NewTypes.reserve(FTy->getNumParams()+1);
9053
Duncan Sandscdb6d922007-09-17 10:26:40 +00009054 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009055 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009056 {
9057 unsigned Idx = 1;
9058 FunctionType::param_iterator I = FTy->param_begin(),
9059 E = FTy->param_end();
9060
9061 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009062 if (Idx == NestIdx)
9063 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009064 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009065
9066 if (I == E)
9067 break;
9068
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009069 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009070 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009071
9072 ++Idx, ++I;
9073 } while (1);
9074 }
9075
9076 // Replace the trampoline call with a direct call. Let the generic
9077 // code sort out any function type mismatches.
9078 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009079 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009080 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9081 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009082 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009083
9084 Instruction *NewCaller;
9085 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009086 NewCaller = InvokeInst::Create(NewCallee,
9087 II->getNormalDest(), II->getUnwindDest(),
9088 NewArgs.begin(), NewArgs.end(),
9089 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009090 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009091 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009092 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009093 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9094 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009095 if (cast<CallInst>(Caller)->isTailCall())
9096 cast<CallInst>(NewCaller)->setTailCall();
9097 cast<CallInst>(NewCaller)->
9098 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009099 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009100 }
9101 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9102 Caller->replaceAllUsesWith(NewCaller);
9103 Caller->eraseFromParent();
9104 RemoveFromWorkList(Caller);
9105 return 0;
9106 }
9107 }
9108
9109 // Replace the trampoline call with a direct call. Since there is no 'nest'
9110 // parameter, there is no need to adjust the argument list. Let the generic
9111 // code sort out any function type mismatches.
9112 Constant *NewCallee =
9113 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9114 CS.setCalledFunction(NewCallee);
9115 return CS.getInstruction();
9116}
9117
Chris Lattner7da52b22006-11-01 04:51:18 +00009118/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9119/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9120/// and a single binop.
9121Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9122 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009123 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9124 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009125 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009126 Value *LHSVal = FirstInst->getOperand(0);
9127 Value *RHSVal = FirstInst->getOperand(1);
9128
9129 const Type *LHSType = LHSVal->getType();
9130 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009131
9132 // Scan to see if all operands are the same opcode, all have one use, and all
9133 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009134 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009135 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009136 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009137 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009138 // types or GEP's with different index types.
9139 I->getOperand(0)->getType() != LHSType ||
9140 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009141 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009142
9143 // If they are CmpInst instructions, check their predicates
9144 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9145 if (cast<CmpInst>(I)->getPredicate() !=
9146 cast<CmpInst>(FirstInst)->getPredicate())
9147 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009148
9149 // Keep track of which operand needs a phi node.
9150 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9151 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009152 }
9153
Chris Lattner53738a42006-11-08 19:42:28 +00009154 // Otherwise, this is safe to transform, determine if it is profitable.
9155
9156 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9157 // Indexes are often folded into load/store instructions, so we don't want to
9158 // hide them behind a phi.
9159 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9160 return 0;
9161
Chris Lattner7da52b22006-11-01 04:51:18 +00009162 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009163 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009164 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009165 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009166 NewLHS = PHINode::Create(LHSType,
9167 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009168 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9169 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009170 InsertNewInstBefore(NewLHS, PN);
9171 LHSVal = NewLHS;
9172 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009173
9174 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009175 NewRHS = PHINode::Create(RHSType,
9176 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009177 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9178 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009179 InsertNewInstBefore(NewRHS, PN);
9180 RHSVal = NewRHS;
9181 }
9182
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009183 // Add all operands to the new PHIs.
9184 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9185 if (NewLHS) {
9186 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9187 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9188 }
9189 if (NewRHS) {
9190 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9191 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9192 }
9193 }
9194
Chris Lattner7da52b22006-11-01 04:51:18 +00009195 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009196 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009197 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009198 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009199 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009200 else {
9201 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009202 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009203 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009204}
9205
Chris Lattner76c73142006-11-01 07:13:54 +00009206/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9207/// of the block that defines it. This means that it must be obvious the value
9208/// of the load is not changed from the point of the load to the end of the
9209/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009210///
9211/// Finally, it is safe, but not profitable, to sink a load targetting a
9212/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9213/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009214static bool isSafeToSinkLoad(LoadInst *L) {
9215 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9216
9217 for (++BBI; BBI != E; ++BBI)
9218 if (BBI->mayWriteToMemory())
9219 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009220
9221 // Check for non-address taken alloca. If not address-taken already, it isn't
9222 // profitable to do this xform.
9223 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9224 bool isAddressTaken = false;
9225 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9226 UI != E; ++UI) {
9227 if (isa<LoadInst>(UI)) continue;
9228 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9229 // If storing TO the alloca, then the address isn't taken.
9230 if (SI->getOperand(1) == AI) continue;
9231 }
9232 isAddressTaken = true;
9233 break;
9234 }
9235
9236 if (!isAddressTaken)
9237 return false;
9238 }
9239
Chris Lattner76c73142006-11-01 07:13:54 +00009240 return true;
9241}
9242
Chris Lattner9fe38862003-06-19 17:00:31 +00009243
Chris Lattnerbac32862004-11-14 19:13:23 +00009244// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9245// operator and they all are only used by the PHI, PHI together their
9246// inputs, and do the operation once, to the result of the PHI.
9247Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9248 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9249
9250 // Scan the instruction, looking for input operations that can be folded away.
9251 // If all input operands to the phi are the same instruction (e.g. a cast from
9252 // the same type or "+42") we can pull the operation through the PHI, reducing
9253 // code size and simplifying code.
9254 Constant *ConstantOp = 0;
9255 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009256 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009257 if (isa<CastInst>(FirstInst)) {
9258 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009259 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009260 // Can fold binop, compare or shift here if the RHS is a constant,
9261 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009262 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009263 if (ConstantOp == 0)
9264 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009265 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9266 isVolatile = LI->isVolatile();
9267 // We can't sink the load if the loaded value could be modified between the
9268 // load and the PHI.
9269 if (LI->getParent() != PN.getIncomingBlock(0) ||
9270 !isSafeToSinkLoad(LI))
9271 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009272 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009273 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009274 return FoldPHIArgBinOpIntoPHI(PN);
9275 // Can't handle general GEPs yet.
9276 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009277 } else {
9278 return 0; // Cannot fold this operation.
9279 }
9280
9281 // Check to see if all arguments are the same operation.
9282 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9283 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9284 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009285 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009286 return 0;
9287 if (CastSrcTy) {
9288 if (I->getOperand(0)->getType() != CastSrcTy)
9289 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009290 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009291 // We can't sink the load if the loaded value could be modified between
9292 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009293 if (LI->isVolatile() != isVolatile ||
9294 LI->getParent() != PN.getIncomingBlock(i) ||
9295 !isSafeToSinkLoad(LI))
9296 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009297
9298 // If the PHI is volatile and its block has multiple successors, sinking
9299 // it would remove a load of the volatile value from the path through the
9300 // other successor.
9301 if (isVolatile &&
9302 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9303 return 0;
9304
9305
Chris Lattnerbac32862004-11-14 19:13:23 +00009306 } else if (I->getOperand(1) != ConstantOp) {
9307 return 0;
9308 }
9309 }
9310
9311 // Okay, they are all the same operation. Create a new PHI node of the
9312 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009313 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9314 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009315 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009316
9317 Value *InVal = FirstInst->getOperand(0);
9318 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009319
9320 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009321 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9322 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9323 if (NewInVal != InVal)
9324 InVal = 0;
9325 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9326 }
9327
9328 Value *PhiVal;
9329 if (InVal) {
9330 // The new PHI unions all of the same values together. This is really
9331 // common, so we handle it intelligently here for compile-time speed.
9332 PhiVal = InVal;
9333 delete NewPN;
9334 } else {
9335 InsertNewInstBefore(NewPN, PN);
9336 PhiVal = NewPN;
9337 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009338
Chris Lattnerbac32862004-11-14 19:13:23 +00009339 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009340 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009341 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009342 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009343 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009344 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009345 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009346 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009347 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9348
9349 // If this was a volatile load that we are merging, make sure to loop through
9350 // and mark all the input loads as non-volatile. If we don't do this, we will
9351 // insert a new volatile load and the old ones will not be deletable.
9352 if (isVolatile)
9353 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9354 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9355
9356 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009357}
Chris Lattnera1be5662002-05-02 17:06:02 +00009358
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009359/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9360/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009361static bool DeadPHICycle(PHINode *PN,
9362 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009363 if (PN->use_empty()) return true;
9364 if (!PN->hasOneUse()) return false;
9365
9366 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009367 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009368 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009369
9370 // Don't scan crazily complex things.
9371 if (PotentiallyDeadPHIs.size() == 16)
9372 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009373
9374 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9375 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009376
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009377 return false;
9378}
9379
Chris Lattnercf5008a2007-11-06 21:52:06 +00009380/// PHIsEqualValue - Return true if this phi node is always equal to
9381/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9382/// z = some value; x = phi (y, z); y = phi (x, z)
9383static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9384 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9385 // See if we already saw this PHI node.
9386 if (!ValueEqualPHIs.insert(PN))
9387 return true;
9388
9389 // Don't scan crazily complex things.
9390 if (ValueEqualPHIs.size() == 16)
9391 return false;
9392
9393 // Scan the operands to see if they are either phi nodes or are equal to
9394 // the value.
9395 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9396 Value *Op = PN->getIncomingValue(i);
9397 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9398 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9399 return false;
9400 } else if (Op != NonPhiInVal)
9401 return false;
9402 }
9403
9404 return true;
9405}
9406
9407
Chris Lattner473945d2002-05-06 18:06:38 +00009408// PHINode simplification
9409//
Chris Lattner7e708292002-06-25 16:13:24 +00009410Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009411 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009412 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009413
Owen Anderson7e057142006-07-10 22:03:18 +00009414 if (Value *V = PN.hasConstantValue())
9415 return ReplaceInstUsesWith(PN, V);
9416
Owen Anderson7e057142006-07-10 22:03:18 +00009417 // If all PHI operands are the same operation, pull them through the PHI,
9418 // reducing code size.
9419 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9420 PN.getIncomingValue(0)->hasOneUse())
9421 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9422 return Result;
9423
9424 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9425 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9426 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009427 if (PN.hasOneUse()) {
9428 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9429 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009430 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009431 PotentiallyDeadPHIs.insert(&PN);
9432 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9433 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9434 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009435
9436 // If this phi has a single use, and if that use just computes a value for
9437 // the next iteration of a loop, delete the phi. This occurs with unused
9438 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9439 // common case here is good because the only other things that catch this
9440 // are induction variable analysis (sometimes) and ADCE, which is only run
9441 // late.
9442 if (PHIUser->hasOneUse() &&
9443 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9444 PHIUser->use_back() == &PN) {
9445 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9446 }
9447 }
Owen Anderson7e057142006-07-10 22:03:18 +00009448
Chris Lattnercf5008a2007-11-06 21:52:06 +00009449 // We sometimes end up with phi cycles that non-obviously end up being the
9450 // same value, for example:
9451 // z = some value; x = phi (y, z); y = phi (x, z)
9452 // where the phi nodes don't necessarily need to be in the same block. Do a
9453 // quick check to see if the PHI node only contains a single non-phi value, if
9454 // so, scan to see if the phi cycle is actually equal to that value.
9455 {
9456 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9457 // Scan for the first non-phi operand.
9458 while (InValNo != NumOperandVals &&
9459 isa<PHINode>(PN.getIncomingValue(InValNo)))
9460 ++InValNo;
9461
9462 if (InValNo != NumOperandVals) {
9463 Value *NonPhiInVal = PN.getOperand(InValNo);
9464
9465 // Scan the rest of the operands to see if there are any conflicts, if so
9466 // there is no need to recursively scan other phis.
9467 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9468 Value *OpVal = PN.getIncomingValue(InValNo);
9469 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9470 break;
9471 }
9472
9473 // If we scanned over all operands, then we have one unique value plus
9474 // phi values. Scan PHI nodes to see if they all merge in each other or
9475 // the value.
9476 if (InValNo == NumOperandVals) {
9477 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9478 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9479 return ReplaceInstUsesWith(PN, NonPhiInVal);
9480 }
9481 }
9482 }
Chris Lattner60921c92003-12-19 05:58:40 +00009483 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009484}
9485
Reid Spencer17212df2006-12-12 09:18:51 +00009486static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9487 Instruction *InsertPoint,
9488 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009489 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9490 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009491 // We must cast correctly to the pointer type. Ensure that we
9492 // sign extend the integer value if it is smaller as this is
9493 // used for address computation.
9494 Instruction::CastOps opcode =
9495 (VTySize < PtrSize ? Instruction::SExt :
9496 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9497 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009498}
9499
Chris Lattnera1be5662002-05-02 17:06:02 +00009500
Chris Lattner7e708292002-06-25 16:13:24 +00009501Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009502 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009503 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009504 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009505 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009506 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009507
Chris Lattnere87597f2004-10-16 18:11:37 +00009508 if (isa<UndefValue>(GEP.getOperand(0)))
9509 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9510
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009511 bool HasZeroPointerIndex = false;
9512 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9513 HasZeroPointerIndex = C->isNullValue();
9514
9515 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009516 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009517
Chris Lattner28977af2004-04-05 01:30:19 +00009518 // Eliminate unneeded casts for indices.
9519 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009520
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009521 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009522 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009523 if (isa<SequentialType>(*GTI)) {
9524 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009525 if (CI->getOpcode() == Instruction::ZExt ||
9526 CI->getOpcode() == Instruction::SExt) {
9527 const Type *SrcTy = CI->getOperand(0)->getType();
9528 // We can eliminate a cast from i32 to i64 iff the target
9529 // is a 32-bit pointer target.
9530 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9531 MadeChange = true;
9532 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009533 }
9534 }
9535 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009536 // If we are using a wider index than needed for this platform, shrink it
9537 // to what we need. If the incoming value needs a cast instruction,
9538 // insert it. This explicit cast can make subsequent optimizations more
9539 // obvious.
9540 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009541 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009542 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009543 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009544 MadeChange = true;
9545 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009546 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9547 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009548 GEP.setOperand(i, Op);
9549 MadeChange = true;
9550 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009551 }
Chris Lattner28977af2004-04-05 01:30:19 +00009552 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009553 }
Chris Lattner28977af2004-04-05 01:30:19 +00009554 if (MadeChange) return &GEP;
9555
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009556 // If this GEP instruction doesn't move the pointer, and if the input operand
9557 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9558 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009559 if (GEP.hasAllZeroIndices()) {
9560 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9561 // If the bitcast is of an allocation, and the allocation will be
9562 // converted to match the type of the cast, don't touch this.
9563 if (isa<AllocationInst>(BCI->getOperand(0))) {
9564 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009565 if (Instruction *I = visitBitCast(*BCI)) {
9566 if (I != BCI) {
9567 I->takeName(BCI);
9568 BCI->getParent()->getInstList().insert(BCI, I);
9569 ReplaceInstUsesWith(*BCI, I);
9570 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009571 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009572 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009573 }
9574 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9575 }
9576 }
9577
Chris Lattner90ac28c2002-08-02 19:29:35 +00009578 // Combine Indices - If the source pointer to this getelementptr instruction
9579 // is a getelementptr instruction, combine the indices of the two
9580 // getelementptr instructions into a single instruction.
9581 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009582 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009583 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009584 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009585
9586 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009587 // Note that if our source is a gep chain itself that we wait for that
9588 // chain to be resolved before we perform this transformation. This
9589 // avoids us creating a TON of code in some cases.
9590 //
9591 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9592 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9593 return 0; // Wait until our source is folded to completion.
9594
Chris Lattner72588fc2007-02-15 22:48:32 +00009595 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009596
9597 // Find out whether the last index in the source GEP is a sequential idx.
9598 bool EndsWithSequential = false;
9599 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9600 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009601 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009602
Chris Lattner90ac28c2002-08-02 19:29:35 +00009603 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009604 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009605 // Replace: gep (gep %P, long B), long A, ...
9606 // With: T = long A+B; gep %P, T, ...
9607 //
Chris Lattner620ce142004-05-07 22:09:22 +00009608 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009609 if (SO1 == Constant::getNullValue(SO1->getType())) {
9610 Sum = GO1;
9611 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9612 Sum = SO1;
9613 } else {
9614 // If they aren't the same type, convert both to an integer of the
9615 // target's pointer size.
9616 if (SO1->getType() != GO1->getType()) {
9617 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009618 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009619 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009620 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009621 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009622 unsigned PS = TD->getPointerSizeInBits();
9623 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009624 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009625 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009626
Duncan Sands514ab342007-11-01 20:53:16 +00009627 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009628 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009629 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009630 } else {
9631 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009632 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9633 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009634 }
9635 }
9636 }
Chris Lattner620ce142004-05-07 22:09:22 +00009637 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9638 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9639 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009640 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +00009641 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009642 }
Chris Lattner28977af2004-04-05 01:30:19 +00009643 }
Chris Lattner620ce142004-05-07 22:09:22 +00009644
9645 // Recycle the GEP we already have if possible.
9646 if (SrcGEPOperands.size() == 2) {
9647 GEP.setOperand(0, SrcGEPOperands[0]);
9648 GEP.setOperand(1, Sum);
9649 return &GEP;
9650 } else {
9651 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9652 SrcGEPOperands.end()-1);
9653 Indices.push_back(Sum);
9654 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9655 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009656 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009657 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009658 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009659 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009660 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9661 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009662 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9663 }
9664
9665 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009666 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9667 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009668
Chris Lattner620ce142004-05-07 22:09:22 +00009669 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009670 // GEP of global variable. If all of the indices for this GEP are
9671 // constants, we can promote this to a constexpr instead of an instruction.
9672
9673 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009674 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009675 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9676 for (; I != E && isa<Constant>(*I); ++I)
9677 Indices.push_back(cast<Constant>(*I));
9678
9679 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009680 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9681 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009682
9683 // Replace all uses of the GEP with the new constexpr...
9684 return ReplaceInstUsesWith(GEP, CE);
9685 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009686 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009687 if (!isa<PointerType>(X->getType())) {
9688 // Not interesting. Source pointer must be a cast from pointer.
9689 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009690 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9691 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009692 //
9693 // This occurs when the program declares an array extern like "int X[];"
9694 //
9695 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9696 const PointerType *XTy = cast<PointerType>(X->getType());
9697 if (const ArrayType *XATy =
9698 dyn_cast<ArrayType>(XTy->getElementType()))
9699 if (const ArrayType *CATy =
9700 dyn_cast<ArrayType>(CPTy->getElementType()))
9701 if (CATy->getElementType() == XATy->getElementType()) {
9702 // At this point, we know that the cast source type is a pointer
9703 // to an array of the same type as the destination pointer
9704 // array. Because the array type is never stepped over (there
9705 // is a leading zero) we can fold the cast into this GEP.
9706 GEP.setOperand(0, X);
9707 return &GEP;
9708 }
9709 } else if (GEP.getNumOperands() == 2) {
9710 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009711 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9712 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009713 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9714 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9715 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009716 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9717 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009718 Value *Idx[2];
9719 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9720 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009721 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009722 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009723 // V and GEP are both pointer types --> BitCast
9724 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009725 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009726
9727 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009728 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009729 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009730 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009731
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009732 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009733 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009734 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009735
9736 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9737 // allow either a mul, shift, or constant here.
9738 Value *NewIdx = 0;
9739 ConstantInt *Scale = 0;
9740 if (ArrayEltSize == 1) {
9741 NewIdx = GEP.getOperand(1);
9742 Scale = ConstantInt::get(NewIdx->getType(), 1);
9743 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009744 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009745 Scale = CI;
9746 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9747 if (Inst->getOpcode() == Instruction::Shl &&
9748 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009749 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9750 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9751 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009752 NewIdx = Inst->getOperand(0);
9753 } else if (Inst->getOpcode() == Instruction::Mul &&
9754 isa<ConstantInt>(Inst->getOperand(1))) {
9755 Scale = cast<ConstantInt>(Inst->getOperand(1));
9756 NewIdx = Inst->getOperand(0);
9757 }
9758 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009759
Chris Lattner7835cdd2005-09-13 18:36:04 +00009760 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009761 // out, perform the transformation. Note, we don't know whether Scale is
9762 // signed or not. We'll use unsigned version of division/modulo
9763 // operation after making sure Scale doesn't have the sign bit set.
9764 if (Scale && Scale->getSExtValue() >= 0LL &&
9765 Scale->getZExtValue() % ArrayEltSize == 0) {
9766 Scale = ConstantInt::get(Scale->getType(),
9767 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009768 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009769 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009770 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009771 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00009772 NewIdx = InsertNewInstBefore(Sc, GEP);
9773 }
9774
9775 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009776 Value *Idx[2];
9777 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9778 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009779 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009780 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009781 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9782 // The NewGEP must be pointer typed, so must the old one -> BitCast
9783 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009784 }
9785 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009786 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009787 }
9788
Chris Lattner8a2a3112001-12-14 16:52:21 +00009789 return 0;
9790}
9791
Chris Lattner0864acf2002-11-04 16:18:53 +00009792Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9793 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009794 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009795 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9796 const Type *NewTy =
9797 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009798 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009799
9800 // Create and insert the replacement instruction...
9801 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009802 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009803 else {
9804 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009805 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009806 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009807
9808 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009809
Chris Lattner0864acf2002-11-04 16:18:53 +00009810 // Scan to the end of the allocation instructions, to skip over a block of
9811 // allocas if possible...
9812 //
9813 BasicBlock::iterator It = New;
9814 while (isa<AllocationInst>(*It)) ++It;
9815
9816 // Now that I is pointing to the first non-allocation-inst in the block,
9817 // insert our getelementptr instruction...
9818 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009819 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009820 Value *Idx[2];
9821 Idx[0] = NullIdx;
9822 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +00009823 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9824 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009825
9826 // Now make everything use the getelementptr instead of the original
9827 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009828 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009829 } else if (isa<UndefValue>(AI.getArraySize())) {
9830 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009831 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009832 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009833
9834 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9835 // Note that we only do this for alloca's, because malloc should allocate and
9836 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009837 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009838 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009839 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9840
Chris Lattner0864acf2002-11-04 16:18:53 +00009841 return 0;
9842}
9843
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009844Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9845 Value *Op = FI.getOperand(0);
9846
Chris Lattner17be6352004-10-18 02:59:09 +00009847 // free undef -> unreachable.
9848 if (isa<UndefValue>(Op)) {
9849 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009850 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009851 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009852 return EraseInstFromFunction(FI);
9853 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009854
Chris Lattner6160e852004-02-28 04:57:37 +00009855 // If we have 'free null' delete the instruction. This can happen in stl code
9856 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009857 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009858 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009859
9860 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9861 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9862 FI.setOperand(0, CI->getOperand(0));
9863 return &FI;
9864 }
9865
9866 // Change free (gep X, 0,0,0,0) into free(X)
9867 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9868 if (GEPI->hasAllZeroIndices()) {
9869 AddToWorkList(GEPI);
9870 FI.setOperand(0, GEPI->getOperand(0));
9871 return &FI;
9872 }
9873 }
9874
9875 // Change free(malloc) into nothing, if the malloc has a single use.
9876 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9877 if (MI->hasOneUse()) {
9878 EraseInstFromFunction(FI);
9879 return EraseInstFromFunction(*MI);
9880 }
Chris Lattner6160e852004-02-28 04:57:37 +00009881
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009882 return 0;
9883}
9884
9885
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009886/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009887static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009888 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009889 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009890 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009891
Devang Patel99db6ad2007-10-18 19:52:32 +00009892 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9893 // Instead of loading constant c string, use corresponding integer value
9894 // directly if string length is small enough.
9895 const std::string &Str = CE->getOperand(0)->getStringValue();
9896 if (!Str.empty()) {
9897 unsigned len = Str.length();
9898 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9899 unsigned numBits = Ty->getPrimitiveSizeInBits();
9900 // Replace LI with immediate integer store.
9901 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009902 APInt StrVal(numBits, 0);
9903 APInt SingleChar(numBits, 0);
9904 if (TD->isLittleEndian()) {
9905 for (signed i = len-1; i >= 0; i--) {
9906 SingleChar = (uint64_t) Str[i];
9907 StrVal = (StrVal << 8) | SingleChar;
9908 }
9909 } else {
9910 for (unsigned i = 0; i < len; i++) {
9911 SingleChar = (uint64_t) Str[i];
9912 StrVal = (StrVal << 8) | SingleChar;
9913 }
9914 // Append NULL at the end.
9915 SingleChar = 0;
9916 StrVal = (StrVal << 8) | SingleChar;
9917 }
9918 Value *NL = ConstantInt::get(StrVal);
9919 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009920 }
9921 }
9922 }
9923
Chris Lattnerb89e0712004-07-13 01:49:43 +00009924 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009925 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009926 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009927
Reid Spencer42230162007-01-22 05:51:25 +00009928 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009929 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009930 // If the source is an array, the code below will not succeed. Check to
9931 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9932 // constants.
9933 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9934 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9935 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009936 Value *Idxs[2];
9937 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9938 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009939 SrcTy = cast<PointerType>(CastOp->getType());
9940 SrcPTy = SrcTy->getElementType();
9941 }
9942
Reid Spencer42230162007-01-22 05:51:25 +00009943 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009944 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009945 // Do not allow turning this into a load of an integer, which is then
9946 // casted to a pointer, this pessimizes pointer analysis a lot.
9947 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009948 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9949 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009950
Chris Lattnerf9527852005-01-31 04:50:46 +00009951 // Okay, we are casting from one integer or pointer type to another of
9952 // the same size. Instead of casting the pointer before the load, cast
9953 // the result of the loaded value.
9954 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9955 CI->getName(),
9956 LI.isVolatile()),LI);
9957 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009958 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009959 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009960 }
9961 }
9962 return 0;
9963}
9964
Chris Lattnerc10aced2004-09-19 18:43:46 +00009965/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009966/// from this value cannot trap. If it is not obviously safe to load from the
9967/// specified pointer, we do a quick local scan of the basic block containing
9968/// ScanFrom, to determine if the address is already accessed.
9969static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009970 // If it is an alloca it is always safe to load from.
9971 if (isa<AllocaInst>(V)) return true;
9972
Duncan Sands46318cd2007-09-19 10:25:38 +00009973 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009974 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009975 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009976 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009977
9978 // Otherwise, be a little bit agressive by scanning the local block where we
9979 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009980 // from/to. If so, the previous load or store would have already trapped,
9981 // so there is no harm doing an extra load (also, CSE will later eliminate
9982 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009983 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9984
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009985 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009986 --BBI;
9987
9988 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9989 if (LI->getOperand(0) == V) return true;
9990 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9991 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009992
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009993 }
Chris Lattner8a375202004-09-19 19:18:10 +00009994 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009995}
9996
Chris Lattner8d2e8882007-08-11 18:48:48 +00009997/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9998/// until we find the underlying object a pointer is referring to or something
9999/// we don't understand. Note that the returned pointer may be offset from the
10000/// input, because we ignore GEP indices.
10001static Value *GetUnderlyingObject(Value *Ptr) {
10002 while (1) {
10003 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10004 if (CE->getOpcode() == Instruction::BitCast ||
10005 CE->getOpcode() == Instruction::GetElementPtr)
10006 Ptr = CE->getOperand(0);
10007 else
10008 return Ptr;
10009 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10010 Ptr = BCI->getOperand(0);
10011 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10012 Ptr = GEP->getOperand(0);
10013 } else {
10014 return Ptr;
10015 }
10016 }
10017}
10018
Chris Lattner833b8a42003-06-26 05:06:25 +000010019Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10020 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010021
Dan Gohman9941f742007-07-20 16:34:21 +000010022 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010023 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10024 if (KnownAlign >
10025 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10026 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010027 LI.setAlignment(KnownAlign);
10028
Chris Lattner37366c12005-05-01 04:24:53 +000010029 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010030 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010031 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010032 return Res;
10033
10034 // None of the following transforms are legal for volatile loads.
10035 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010036
Chris Lattner62f254d2005-09-12 22:00:15 +000010037 if (&LI.getParent()->front() != &LI) {
10038 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010039 // If the instruction immediately before this is a store to the same
10040 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010041 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10042 if (SI->getOperand(1) == LI.getOperand(0))
10043 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010044 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10045 if (LIB->getOperand(0) == LI.getOperand(0))
10046 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010047 }
Chris Lattner37366c12005-05-01 04:24:53 +000010048
Christopher Lambb15147e2007-12-29 07:56:53 +000010049 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10050 const Value *GEPI0 = GEPI->getOperand(0);
10051 // TODO: Consider a target hook for valid address spaces for this xform.
10052 if (isa<ConstantPointerNull>(GEPI0) &&
10053 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010054 // Insert a new store to null instruction before the load to indicate
10055 // that this code is not reachable. We do this instead of inserting
10056 // an unreachable instruction directly because we cannot modify the
10057 // CFG.
10058 new StoreInst(UndefValue::get(LI.getType()),
10059 Constant::getNullValue(Op->getType()), &LI);
10060 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10061 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010062 }
Chris Lattner37366c12005-05-01 04:24:53 +000010063
Chris Lattnere87597f2004-10-16 18:11:37 +000010064 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010065 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010066 // TODO: Consider a target hook for valid address spaces for this xform.
10067 if (isa<UndefValue>(C) || (C->isNullValue() &&
10068 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010069 // Insert a new store to null instruction before the load to indicate that
10070 // this code is not reachable. We do this instead of inserting an
10071 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010072 new StoreInst(UndefValue::get(LI.getType()),
10073 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010074 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010075 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010076
Chris Lattnere87597f2004-10-16 18:11:37 +000010077 // Instcombine load (constant global) into the value loaded.
10078 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010079 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010080 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010081
Chris Lattnere87597f2004-10-16 18:11:37 +000010082 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010083 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010084 if (CE->getOpcode() == Instruction::GetElementPtr) {
10085 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010086 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010087 if (Constant *V =
10088 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010089 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010090 if (CE->getOperand(0)->isNullValue()) {
10091 // Insert a new store to null instruction before the load to indicate
10092 // that this code is not reachable. We do this instead of inserting
10093 // an unreachable instruction directly because we cannot modify the
10094 // CFG.
10095 new StoreInst(UndefValue::get(LI.getType()),
10096 Constant::getNullValue(Op->getType()), &LI);
10097 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10098 }
10099
Reid Spencer3da59db2006-11-27 01:05:10 +000010100 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010101 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010102 return Res;
10103 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010104 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010105 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010106
10107 // If this load comes from anywhere in a constant global, and if the global
10108 // is all undef or zero, we know what it loads.
10109 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10110 if (GV->isConstant() && GV->hasInitializer()) {
10111 if (GV->getInitializer()->isNullValue())
10112 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10113 else if (isa<UndefValue>(GV->getInitializer()))
10114 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10115 }
10116 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010117
Chris Lattner37366c12005-05-01 04:24:53 +000010118 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010119 // Change select and PHI nodes to select values instead of addresses: this
10120 // helps alias analysis out a lot, allows many others simplifications, and
10121 // exposes redundancy in the code.
10122 //
10123 // Note that we cannot do the transformation unless we know that the
10124 // introduced loads cannot trap! Something like this is valid as long as
10125 // the condition is always false: load (select bool %C, int* null, int* %G),
10126 // but it would not be valid if we transformed it to load from null
10127 // unconditionally.
10128 //
10129 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10130 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010131 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10132 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010133 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010134 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010135 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010136 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010137 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010138 }
10139
Chris Lattner684fe212004-09-23 15:46:00 +000010140 // load (select (cond, null, P)) -> load P
10141 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10142 if (C->isNullValue()) {
10143 LI.setOperand(0, SI->getOperand(2));
10144 return &LI;
10145 }
10146
10147 // load (select (cond, P, null)) -> load P
10148 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10149 if (C->isNullValue()) {
10150 LI.setOperand(0, SI->getOperand(1));
10151 return &LI;
10152 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010153 }
10154 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010155 return 0;
10156}
10157
Reid Spencer55af2b52007-01-19 21:20:31 +000010158/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010159/// when possible.
10160static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10161 User *CI = cast<User>(SI.getOperand(1));
10162 Value *CastOp = CI->getOperand(0);
10163
10164 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10165 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10166 const Type *SrcPTy = SrcTy->getElementType();
10167
Reid Spencer42230162007-01-22 05:51:25 +000010168 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010169 // If the source is an array, the code below will not succeed. Check to
10170 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10171 // constants.
10172 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10173 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10174 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010175 Value* Idxs[2];
10176 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10177 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010178 SrcTy = cast<PointerType>(CastOp->getType());
10179 SrcPTy = SrcTy->getElementType();
10180 }
10181
Reid Spencer67f827c2007-01-20 23:35:48 +000010182 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10183 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10184 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010185
10186 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010187 // the same size. Instead of casting the pointer before
10188 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010189 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010190 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010191 Instruction::CastOps opcode = Instruction::BitCast;
10192 const Type* CastSrcTy = SIOp0->getType();
10193 const Type* CastDstTy = SrcPTy;
10194 if (isa<PointerType>(CastDstTy)) {
10195 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010196 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010197 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010198 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010199 opcode = Instruction::PtrToInt;
10200 }
10201 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010202 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010203 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010204 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010205 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010206 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010207 return new StoreInst(NewCast, CastOp);
10208 }
10209 }
10210 }
10211 return 0;
10212}
10213
Chris Lattner2f503e62005-01-31 05:36:43 +000010214Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10215 Value *Val = SI.getOperand(0);
10216 Value *Ptr = SI.getOperand(1);
10217
10218 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010219 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010220 ++NumCombined;
10221 return 0;
10222 }
Chris Lattner836692d2007-01-15 06:51:56 +000010223
10224 // If the RHS is an alloca with a single use, zapify the store, making the
10225 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010226 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010227 if (isa<AllocaInst>(Ptr)) {
10228 EraseInstFromFunction(SI);
10229 ++NumCombined;
10230 return 0;
10231 }
10232
10233 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10234 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10235 GEP->getOperand(0)->hasOneUse()) {
10236 EraseInstFromFunction(SI);
10237 ++NumCombined;
10238 return 0;
10239 }
10240 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010241
Dan Gohman9941f742007-07-20 16:34:21 +000010242 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010243 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10244 if (KnownAlign >
10245 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10246 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010247 SI.setAlignment(KnownAlign);
10248
Chris Lattner9ca96412006-02-08 03:25:32 +000010249 // Do really simple DSE, to catch cases where there are several consequtive
10250 // stores to the same location, separated by a few arithmetic operations. This
10251 // situation often occurs with bitfield accesses.
10252 BasicBlock::iterator BBI = &SI;
10253 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10254 --ScanInsts) {
10255 --BBI;
10256
10257 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10258 // Prev store isn't volatile, and stores to the same location?
10259 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10260 ++NumDeadStore;
10261 ++BBI;
10262 EraseInstFromFunction(*PrevSI);
10263 continue;
10264 }
10265 break;
10266 }
10267
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010268 // If this is a load, we have to stop. However, if the loaded value is from
10269 // the pointer we're loading and is producing the pointer we're storing,
10270 // then *this* store is dead (X = load P; store X -> P).
10271 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010272 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010273 EraseInstFromFunction(SI);
10274 ++NumCombined;
10275 return 0;
10276 }
10277 // Otherwise, this is a load from some other location. Stores before it
10278 // may not be dead.
10279 break;
10280 }
10281
Chris Lattner9ca96412006-02-08 03:25:32 +000010282 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010283 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010284 break;
10285 }
10286
10287
10288 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010289
10290 // store X, null -> turns into 'unreachable' in SimplifyCFG
10291 if (isa<ConstantPointerNull>(Ptr)) {
10292 if (!isa<UndefValue>(Val)) {
10293 SI.setOperand(0, UndefValue::get(Val->getType()));
10294 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010295 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010296 ++NumCombined;
10297 }
10298 return 0; // Do not modify these!
10299 }
10300
10301 // store undef, Ptr -> noop
10302 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010303 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010304 ++NumCombined;
10305 return 0;
10306 }
10307
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010308 // If the pointer destination is a cast, see if we can fold the cast into the
10309 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010310 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010311 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10312 return Res;
10313 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010314 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010315 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10316 return Res;
10317
Chris Lattner408902b2005-09-12 23:23:25 +000010318
10319 // If this store is the last instruction in the basic block, and if the block
10320 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010321 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010322 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010323 if (BI->isUnconditional())
10324 if (SimplifyStoreAtEndOfBlock(SI))
10325 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010326
Chris Lattner2f503e62005-01-31 05:36:43 +000010327 return 0;
10328}
10329
Chris Lattner3284d1f2007-04-15 00:07:55 +000010330/// SimplifyStoreAtEndOfBlock - Turn things like:
10331/// if () { *P = v1; } else { *P = v2 }
10332/// into a phi node with a store in the successor.
10333///
Chris Lattner31755a02007-04-15 01:02:18 +000010334/// Simplify things like:
10335/// *P = v1; if () { *P = v2; }
10336/// into a phi node with a store in the successor.
10337///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010338bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10339 BasicBlock *StoreBB = SI.getParent();
10340
10341 // Check to see if the successor block has exactly two incoming edges. If
10342 // so, see if the other predecessor contains a store to the same location.
10343 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010344 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010345
10346 // Determine whether Dest has exactly two predecessors and, if so, compute
10347 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010348 pred_iterator PI = pred_begin(DestBB);
10349 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010350 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010351 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010352 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010353 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010354 return false;
10355
10356 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010357 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010358 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010359 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010360 }
Chris Lattner31755a02007-04-15 01:02:18 +000010361 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010362 return false;
10363
10364
Chris Lattner31755a02007-04-15 01:02:18 +000010365 // Verify that the other block ends in a branch and is not otherwise empty.
10366 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010367 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010368 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010369 return false;
10370
Chris Lattner31755a02007-04-15 01:02:18 +000010371 // If the other block ends in an unconditional branch, check for the 'if then
10372 // else' case. there is an instruction before the branch.
10373 StoreInst *OtherStore = 0;
10374 if (OtherBr->isUnconditional()) {
10375 // If this isn't a store, or isn't a store to the same location, bail out.
10376 --BBI;
10377 OtherStore = dyn_cast<StoreInst>(BBI);
10378 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10379 return false;
10380 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010381 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010382 // destinations is StoreBB, then we have the if/then case.
10383 if (OtherBr->getSuccessor(0) != StoreBB &&
10384 OtherBr->getSuccessor(1) != StoreBB)
10385 return false;
10386
10387 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010388 // if/then triangle. See if there is a store to the same ptr as SI that
10389 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010390 for (;; --BBI) {
10391 // Check to see if we find the matching store.
10392 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10393 if (OtherStore->getOperand(1) != SI.getOperand(1))
10394 return false;
10395 break;
10396 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010397 // If we find something that may be using the stored value, or if we run
10398 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010399 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10400 BBI == OtherBB->begin())
10401 return false;
10402 }
10403
10404 // In order to eliminate the store in OtherBr, we have to
10405 // make sure nothing reads the stored value in StoreBB.
10406 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10407 // FIXME: This should really be AA driven.
10408 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10409 return false;
10410 }
10411 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010412
Chris Lattner31755a02007-04-15 01:02:18 +000010413 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010414 Value *MergedVal = OtherStore->getOperand(0);
10415 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010416 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010417 PN->reserveOperandSpace(2);
10418 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010419 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10420 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010421 }
10422
10423 // Advance to a place where it is safe to insert the new store and
10424 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000010425 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010426 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10427 OtherStore->isVolatile()), *BBI);
10428
10429 // Nuke the old stores.
10430 EraseInstFromFunction(SI);
10431 EraseInstFromFunction(*OtherStore);
10432 ++NumCombined;
10433 return true;
10434}
10435
Chris Lattner2f503e62005-01-31 05:36:43 +000010436
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010437Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10438 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010439 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010440 BasicBlock *TrueDest;
10441 BasicBlock *FalseDest;
10442 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10443 !isa<Constant>(X)) {
10444 // Swap Destinations and condition...
10445 BI.setCondition(X);
10446 BI.setSuccessor(0, FalseDest);
10447 BI.setSuccessor(1, TrueDest);
10448 return &BI;
10449 }
10450
Reid Spencere4d87aa2006-12-23 06:05:41 +000010451 // Cannonicalize fcmp_one -> fcmp_oeq
10452 FCmpInst::Predicate FPred; Value *Y;
10453 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10454 TrueDest, FalseDest)))
10455 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10456 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10457 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010458 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010459 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10460 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010461 // Swap Destinations and condition...
10462 BI.setCondition(NewSCC);
10463 BI.setSuccessor(0, FalseDest);
10464 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010465 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010466 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010467 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010468 return &BI;
10469 }
10470
10471 // Cannonicalize icmp_ne -> icmp_eq
10472 ICmpInst::Predicate IPred;
10473 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10474 TrueDest, FalseDest)))
10475 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10476 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10477 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10478 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010479 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010480 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10481 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010482 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010483 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010484 BI.setSuccessor(0, FalseDest);
10485 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010486 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010487 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010488 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010489 return &BI;
10490 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010491
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010492 return 0;
10493}
Chris Lattner0864acf2002-11-04 16:18:53 +000010494
Chris Lattner46238a62004-07-03 00:26:11 +000010495Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10496 Value *Cond = SI.getCondition();
10497 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10498 if (I->getOpcode() == Instruction::Add)
10499 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10500 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10501 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010502 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010503 AddRHS));
10504 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010505 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010506 return &SI;
10507 }
10508 }
10509 return 0;
10510}
10511
Chris Lattner220b0cf2006-03-05 00:22:33 +000010512/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10513/// is to leave as a vector operation.
10514static bool CheapToScalarize(Value *V, bool isConstant) {
10515 if (isa<ConstantAggregateZero>(V))
10516 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010517 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010518 if (isConstant) return true;
10519 // If all elts are the same, we can extract.
10520 Constant *Op0 = C->getOperand(0);
10521 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10522 if (C->getOperand(i) != Op0)
10523 return false;
10524 return true;
10525 }
10526 Instruction *I = dyn_cast<Instruction>(V);
10527 if (!I) return false;
10528
10529 // Insert element gets simplified to the inserted element or is deleted if
10530 // this is constant idx extract element and its a constant idx insertelt.
10531 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10532 isa<ConstantInt>(I->getOperand(2)))
10533 return true;
10534 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10535 return true;
10536 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10537 if (BO->hasOneUse() &&
10538 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10539 CheapToScalarize(BO->getOperand(1), isConstant)))
10540 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010541 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10542 if (CI->hasOneUse() &&
10543 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10544 CheapToScalarize(CI->getOperand(1), isConstant)))
10545 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010546
10547 return false;
10548}
10549
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010550/// Read and decode a shufflevector mask.
10551///
10552/// It turns undef elements into values that are larger than the number of
10553/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010554static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10555 unsigned NElts = SVI->getType()->getNumElements();
10556 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10557 return std::vector<unsigned>(NElts, 0);
10558 if (isa<UndefValue>(SVI->getOperand(2)))
10559 return std::vector<unsigned>(NElts, 2*NElts);
10560
10561 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010562 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010563 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10564 if (isa<UndefValue>(CP->getOperand(i)))
10565 Result.push_back(NElts*2); // undef -> 8
10566 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010567 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010568 return Result;
10569}
10570
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010571/// FindScalarElement - Given a vector and an element number, see if the scalar
10572/// value is already around as a register, for example if it were inserted then
10573/// extracted from the vector.
10574static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010575 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10576 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010577 unsigned Width = PTy->getNumElements();
10578 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010579 return UndefValue::get(PTy->getElementType());
10580
10581 if (isa<UndefValue>(V))
10582 return UndefValue::get(PTy->getElementType());
10583 else if (isa<ConstantAggregateZero>(V))
10584 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010585 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010586 return CP->getOperand(EltNo);
10587 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10588 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010589 if (!isa<ConstantInt>(III->getOperand(2)))
10590 return 0;
10591 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010592
10593 // If this is an insert to the element we are looking for, return the
10594 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010595 if (EltNo == IIElt)
10596 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010597
10598 // Otherwise, the insertelement doesn't modify the value, recurse on its
10599 // vector input.
10600 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010601 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010602 unsigned InEl = getShuffleMask(SVI)[EltNo];
10603 if (InEl < Width)
10604 return FindScalarElement(SVI->getOperand(0), InEl);
10605 else if (InEl < Width*2)
10606 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10607 else
10608 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010609 }
10610
10611 // Otherwise, we don't know.
10612 return 0;
10613}
10614
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010615Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010616
Dan Gohman07a96762007-07-16 14:29:03 +000010617 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010618 if (isa<UndefValue>(EI.getOperand(0)))
10619 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10620
Dan Gohman07a96762007-07-16 14:29:03 +000010621 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010622 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10623 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10624
Reid Spencer9d6565a2007-02-15 02:26:10 +000010625 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010626 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010627 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010628 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010629 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010630 if (C->getOperand(i) != op0) {
10631 op0 = 0;
10632 break;
10633 }
10634 if (op0)
10635 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010636 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010637
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010638 // If extracting a specified index from the vector, see if we can recursively
10639 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010640 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010641 unsigned IndexVal = IdxC->getZExtValue();
10642 unsigned VectorWidth =
10643 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10644
10645 // If this is extracting an invalid index, turn this into undef, to avoid
10646 // crashing the code below.
10647 if (IndexVal >= VectorWidth)
10648 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10649
Chris Lattner867b99f2006-10-05 06:55:50 +000010650 // This instruction only demands the single element from the input vector.
10651 // If the input vector has a single use, simplify it based on this use
10652 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010653 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010654 uint64_t UndefElts;
10655 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010656 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010657 UndefElts)) {
10658 EI.setOperand(0, V);
10659 return &EI;
10660 }
10661 }
10662
Reid Spencerb83eb642006-10-20 07:07:24 +000010663 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010664 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010665
10666 // If the this extractelement is directly using a bitcast from a vector of
10667 // the same number of elements, see if we can find the source element from
10668 // it. In this case, we will end up needing to bitcast the scalars.
10669 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10670 if (const VectorType *VT =
10671 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10672 if (VT->getNumElements() == VectorWidth)
10673 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10674 return new BitCastInst(Elt, EI.getType());
10675 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010676 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010677
Chris Lattner73fa49d2006-05-25 22:53:38 +000010678 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010679 if (I->hasOneUse()) {
10680 // Push extractelement into predecessor operation if legal and
10681 // profitable to do so
10682 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010683 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10684 if (CheapToScalarize(BO, isConstantElt)) {
10685 ExtractElementInst *newEI0 =
10686 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10687 EI.getName()+".lhs");
10688 ExtractElementInst *newEI1 =
10689 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10690 EI.getName()+".rhs");
10691 InsertNewInstBefore(newEI0, EI);
10692 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010693 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000010694 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010695 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010696 unsigned AS =
10697 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010698 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10699 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010700 GetElementPtrInst *GEP =
10701 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010702 InsertNewInstBefore(GEP, EI);
10703 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010704 }
10705 }
10706 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10707 // Extracting the inserted element?
10708 if (IE->getOperand(2) == EI.getOperand(1))
10709 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10710 // If the inserted and extracted elements are constants, they must not
10711 // be the same value, extract from the pre-inserted value instead.
10712 if (isa<Constant>(IE->getOperand(2)) &&
10713 isa<Constant>(EI.getOperand(1))) {
10714 AddUsesToWorkList(EI);
10715 EI.setOperand(0, IE->getOperand(0));
10716 return &EI;
10717 }
10718 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10719 // If this is extracting an element from a shufflevector, figure out where
10720 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010721 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10722 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010723 Value *Src;
10724 if (SrcIdx < SVI->getType()->getNumElements())
10725 Src = SVI->getOperand(0);
10726 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10727 SrcIdx -= SVI->getType()->getNumElements();
10728 Src = SVI->getOperand(1);
10729 } else {
10730 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010731 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010732 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010733 }
10734 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010735 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010736 return 0;
10737}
10738
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010739/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10740/// elements from either LHS or RHS, return the shuffle mask and true.
10741/// Otherwise, return false.
10742static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10743 std::vector<Constant*> &Mask) {
10744 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10745 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010746 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010747
10748 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010749 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010750 return true;
10751 } else if (V == LHS) {
10752 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010753 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010754 return true;
10755 } else if (V == RHS) {
10756 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010757 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010758 return true;
10759 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10760 // If this is an insert of an extract from some other vector, include it.
10761 Value *VecOp = IEI->getOperand(0);
10762 Value *ScalarOp = IEI->getOperand(1);
10763 Value *IdxOp = IEI->getOperand(2);
10764
Chris Lattnerd929f062006-04-27 21:14:21 +000010765 if (!isa<ConstantInt>(IdxOp))
10766 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010767 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010768
10769 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10770 // Okay, we can handle this if the vector we are insertinting into is
10771 // transitively ok.
10772 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10773 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010774 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010775 return true;
10776 }
10777 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10778 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010779 EI->getOperand(0)->getType() == V->getType()) {
10780 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010781 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010782
10783 // This must be extracting from either LHS or RHS.
10784 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10785 // Okay, we can handle this if the vector we are insertinting into is
10786 // transitively ok.
10787 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10788 // If so, update the mask to reflect the inserted value.
10789 if (EI->getOperand(0) == LHS) {
10790 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010791 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010792 } else {
10793 assert(EI->getOperand(0) == RHS);
10794 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010795 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010796
10797 }
10798 return true;
10799 }
10800 }
10801 }
10802 }
10803 }
10804 // TODO: Handle shufflevector here!
10805
10806 return false;
10807}
10808
10809/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10810/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10811/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010812static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010813 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010814 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010815 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010816 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010817 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010818
10819 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010820 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010821 return V;
10822 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010823 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010824 return V;
10825 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10826 // If this is an insert of an extract from some other vector, include it.
10827 Value *VecOp = IEI->getOperand(0);
10828 Value *ScalarOp = IEI->getOperand(1);
10829 Value *IdxOp = IEI->getOperand(2);
10830
10831 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10832 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10833 EI->getOperand(0)->getType() == V->getType()) {
10834 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010835 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10836 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010837
10838 // Either the extracted from or inserted into vector must be RHSVec,
10839 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010840 if (EI->getOperand(0) == RHS || RHS == 0) {
10841 RHS = EI->getOperand(0);
10842 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010843 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010844 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010845 return V;
10846 }
10847
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010848 if (VecOp == RHS) {
10849 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010850 // Everything but the extracted element is replaced with the RHS.
10851 for (unsigned i = 0; i != NumElts; ++i) {
10852 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010853 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010854 }
10855 return V;
10856 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010857
10858 // If this insertelement is a chain that comes from exactly these two
10859 // vectors, return the vector and the effective shuffle.
10860 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10861 return EI->getOperand(0);
10862
Chris Lattnerefb47352006-04-15 01:39:45 +000010863 }
10864 }
10865 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010866 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010867
10868 // Otherwise, can't do anything fancy. Return an identity vector.
10869 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010870 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010871 return V;
10872}
10873
10874Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10875 Value *VecOp = IE.getOperand(0);
10876 Value *ScalarOp = IE.getOperand(1);
10877 Value *IdxOp = IE.getOperand(2);
10878
Chris Lattner599ded12007-04-09 01:11:16 +000010879 // Inserting an undef or into an undefined place, remove this.
10880 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10881 ReplaceInstUsesWith(IE, VecOp);
10882
Chris Lattnerefb47352006-04-15 01:39:45 +000010883 // If the inserted element was extracted from some other vector, and if the
10884 // indexes are constant, try to turn this into a shufflevector operation.
10885 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10886 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10887 EI->getOperand(0)->getType() == IE.getType()) {
10888 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010889 unsigned ExtractedIdx =
10890 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010891 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010892
10893 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10894 return ReplaceInstUsesWith(IE, VecOp);
10895
10896 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10897 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10898
10899 // If we are extracting a value from a vector, then inserting it right
10900 // back into the same place, just use the input vector.
10901 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10902 return ReplaceInstUsesWith(IE, VecOp);
10903
10904 // We could theoretically do this for ANY input. However, doing so could
10905 // turn chains of insertelement instructions into a chain of shufflevector
10906 // instructions, and right now we do not merge shufflevectors. As such,
10907 // only do this in a situation where it is clear that there is benefit.
10908 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10909 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10910 // the values of VecOp, except then one read from EIOp0.
10911 // Build a new shuffle mask.
10912 std::vector<Constant*> Mask;
10913 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010914 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010915 else {
10916 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010917 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010918 NumVectorElts));
10919 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010920 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010921 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010922 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010923 }
10924
10925 // If this insertelement isn't used by some other insertelement, turn it
10926 // (and any insertelements it points to), into one big shuffle.
10927 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10928 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010929 Value *RHS = 0;
10930 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10931 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10932 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010933 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010934 }
10935 }
10936 }
10937
10938 return 0;
10939}
10940
10941
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010942Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10943 Value *LHS = SVI.getOperand(0);
10944 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010945 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010946
10947 bool MadeChange = false;
10948
Chris Lattner867b99f2006-10-05 06:55:50 +000010949 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010950 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010951 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10952
Chris Lattnere4929dd2007-01-05 07:36:08 +000010953 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010954 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010955 if (isa<UndefValue>(SVI.getOperand(1))) {
10956 // Scan to see if there are any references to the RHS. If so, replace them
10957 // with undef element refs and set MadeChange to true.
10958 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10959 if (Mask[i] >= e && Mask[i] != 2*e) {
10960 Mask[i] = 2*e;
10961 MadeChange = true;
10962 }
10963 }
10964
10965 if (MadeChange) {
10966 // Remap any references to RHS to use LHS.
10967 std::vector<Constant*> Elts;
10968 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10969 if (Mask[i] == 2*e)
10970 Elts.push_back(UndefValue::get(Type::Int32Ty));
10971 else
10972 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10973 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010974 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010975 }
10976 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010977
Chris Lattner863bcff2006-05-25 23:48:38 +000010978 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10979 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10980 if (LHS == RHS || isa<UndefValue>(LHS)) {
10981 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010982 // shuffle(undef,undef,mask) -> undef.
10983 return ReplaceInstUsesWith(SVI, LHS);
10984 }
10985
Chris Lattner863bcff2006-05-25 23:48:38 +000010986 // Remap any references to RHS to use LHS.
10987 std::vector<Constant*> Elts;
10988 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010989 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010990 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010991 else {
10992 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10993 (Mask[i] < e && isa<UndefValue>(LHS)))
10994 Mask[i] = 2*e; // Turn into undef.
10995 else
10996 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010997 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010998 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010999 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011000 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011001 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011002 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011003 LHS = SVI.getOperand(0);
11004 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011005 MadeChange = true;
11006 }
11007
Chris Lattner7b2e27922006-05-26 00:29:06 +000011008 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011009 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011010
Chris Lattner863bcff2006-05-25 23:48:38 +000011011 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11012 if (Mask[i] >= e*2) continue; // Ignore undef values.
11013 // Is this an identity shuffle of the LHS value?
11014 isLHSID &= (Mask[i] == i);
11015
11016 // Is this an identity shuffle of the RHS value?
11017 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011018 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011019
Chris Lattner863bcff2006-05-25 23:48:38 +000011020 // Eliminate identity shuffles.
11021 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11022 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011023
Chris Lattner7b2e27922006-05-26 00:29:06 +000011024 // If the LHS is a shufflevector itself, see if we can combine it with this
11025 // one without producing an unusual shuffle. Here we are really conservative:
11026 // we are absolutely afraid of producing a shuffle mask not in the input
11027 // program, because the code gen may not be smart enough to turn a merged
11028 // shuffle into two specific shuffles: it may produce worse code. As such,
11029 // we only merge two shuffles if the result is one of the two input shuffle
11030 // masks. In this case, merging the shuffles just removes one instruction,
11031 // which we know is safe. This is good for things like turning:
11032 // (splat(splat)) -> splat.
11033 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11034 if (isa<UndefValue>(RHS)) {
11035 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11036
11037 std::vector<unsigned> NewMask;
11038 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11039 if (Mask[i] >= 2*e)
11040 NewMask.push_back(2*e);
11041 else
11042 NewMask.push_back(LHSMask[Mask[i]]);
11043
11044 // If the result mask is equal to the src shuffle or this shuffle mask, do
11045 // the replacement.
11046 if (NewMask == LHSMask || NewMask == Mask) {
11047 std::vector<Constant*> Elts;
11048 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11049 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011050 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011051 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011052 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011053 }
11054 }
11055 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11056 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011057 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011058 }
11059 }
11060 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011061
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011062 return MadeChange ? &SVI : 0;
11063}
11064
11065
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011066
Chris Lattnerea1c4542004-12-08 23:43:58 +000011067
11068/// TryToSinkInstruction - Try to move the specified instruction from its
11069/// current block into the beginning of DestBlock, which can only happen if it's
11070/// safe to move the instruction past all of the instructions between it and the
11071/// end of its block.
11072static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11073 assert(I->hasOneUse() && "Invariants didn't hold!");
11074
Chris Lattner108e9022005-10-27 17:13:11 +000011075 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011076 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11077 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011078
Chris Lattnerea1c4542004-12-08 23:43:58 +000011079 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011080 if (isa<AllocaInst>(I) && I->getParent() ==
11081 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011082 return false;
11083
Chris Lattner96a52a62004-12-09 07:14:34 +000011084 // We can only sink load instructions if there is nothing between the load and
11085 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011086 if (I->mayReadFromMemory()) {
11087 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011088 Scan != E; ++Scan)
11089 if (Scan->mayWriteToMemory())
11090 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011091 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011092
Dan Gohman02dea8b2008-05-23 21:05:58 +000011093 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011094
Chris Lattner4bc5f802005-08-08 19:11:57 +000011095 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011096 ++NumSunkInst;
11097 return true;
11098}
11099
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011100
11101/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11102/// all reachable code to the worklist.
11103///
11104/// This has a couple of tricks to make the code faster and more powerful. In
11105/// particular, we constant fold and DCE instructions as we go, to avoid adding
11106/// them to the worklist (this significantly speeds up instcombine on code where
11107/// many instructions are dead or constant). Additionally, if we find a branch
11108/// whose condition is a known constant, we only visit the reachable successors.
11109///
11110static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011111 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011112 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011113 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011114 std::vector<BasicBlock*> Worklist;
11115 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011116
Chris Lattner2c7718a2007-03-23 19:17:18 +000011117 while (!Worklist.empty()) {
11118 BB = Worklist.back();
11119 Worklist.pop_back();
11120
11121 // We have now visited this block! If we've already been here, ignore it.
11122 if (!Visited.insert(BB)) continue;
11123
11124 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11125 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011126
Chris Lattner2c7718a2007-03-23 19:17:18 +000011127 // DCE instruction if trivially dead.
11128 if (isInstructionTriviallyDead(Inst)) {
11129 ++NumDeadInst;
11130 DOUT << "IC: DCE: " << *Inst;
11131 Inst->eraseFromParent();
11132 continue;
11133 }
11134
11135 // ConstantProp instruction if trivially constant.
11136 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11137 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11138 Inst->replaceAllUsesWith(C);
11139 ++NumConstProp;
11140 Inst->eraseFromParent();
11141 continue;
11142 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011143
Chris Lattner2c7718a2007-03-23 19:17:18 +000011144 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011145 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011146
11147 // Recursively visit successors. If this is a branch or switch on a
11148 // constant, only visit the reachable successor.
11149 TerminatorInst *TI = BB->getTerminator();
11150 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11151 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11152 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011153 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011154 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011155 continue;
11156 }
11157 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11158 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11159 // See if this is an explicit destination.
11160 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11161 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011162 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011163 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011164 continue;
11165 }
11166
11167 // Otherwise it is the default destination.
11168 Worklist.push_back(SI->getSuccessor(0));
11169 continue;
11170 }
11171 }
11172
11173 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11174 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011175 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011176}
11177
Chris Lattnerec9c3582007-03-03 02:04:50 +000011178bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011179 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011180 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011181
11182 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11183 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011184
Chris Lattnerb3d59702005-07-07 20:40:38 +000011185 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011186 // Do a depth-first traversal of the function, populate the worklist with
11187 // the reachable instructions. Ignore blocks that are not reachable. Keep
11188 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011189 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011190 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011191
Chris Lattnerb3d59702005-07-07 20:40:38 +000011192 // Do a quick scan over the function. If we find any blocks that are
11193 // unreachable, remove any instructions inside of them. This prevents
11194 // the instcombine code from having to deal with some bad special cases.
11195 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11196 if (!Visited.count(BB)) {
11197 Instruction *Term = BB->getTerminator();
11198 while (Term != BB->begin()) { // Remove instrs bottom-up
11199 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011200
Bill Wendlingb7427032006-11-26 09:46:52 +000011201 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011202 ++NumDeadInst;
11203
11204 if (!I->use_empty())
11205 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11206 I->eraseFromParent();
11207 }
11208 }
11209 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011210
Chris Lattnerdbab3862007-03-02 21:28:56 +000011211 while (!Worklist.empty()) {
11212 Instruction *I = RemoveOneFromWorkList();
11213 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011214
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011215 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011216 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011217 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011218 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011219 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011220 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011221
Bill Wendlingb7427032006-11-26 09:46:52 +000011222 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011223
11224 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011225 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011226 continue;
11227 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011228
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011229 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011230 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011231 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011232
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011233 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011234 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011235 ReplaceInstUsesWith(*I, C);
11236
Chris Lattner62b14df2002-09-02 04:59:56 +000011237 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011238 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011239 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011240 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011241 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011242
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000011243 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11244 // See if we can constant fold its operands.
11245 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11246 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11247 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11248 i->set(NewC);
11249 }
11250 }
11251 }
11252
Chris Lattnerea1c4542004-12-08 23:43:58 +000011253 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011254 // FIXME: Remove GetResultInst test when first class support for aggregates
11255 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011256 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011257 BasicBlock *BB = I->getParent();
11258 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11259 if (UserParent != BB) {
11260 bool UserIsSuccessor = false;
11261 // See if the user is one of our successors.
11262 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11263 if (*SI == UserParent) {
11264 UserIsSuccessor = true;
11265 break;
11266 }
11267
11268 // If the user is one of our immediate successors, and if that successor
11269 // only has us as a predecessors (we'd have to split the critical edge
11270 // otherwise), we can keep going.
11271 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11272 next(pred_begin(UserParent)) == pred_end(UserParent))
11273 // Okay, the CFG is simple enough, try to sink this instruction.
11274 Changed |= TryToSinkInstruction(I, UserParent);
11275 }
11276 }
11277
Chris Lattner8a2a3112001-12-14 16:52:21 +000011278 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011279#ifndef NDEBUG
11280 std::string OrigI;
11281#endif
11282 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011283 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011284 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011285 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011286 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011287 DOUT << "IC: Old = " << *I
11288 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011289
Chris Lattnerf523d062004-06-09 05:08:07 +000011290 // Everything uses the new instruction now.
11291 I->replaceAllUsesWith(Result);
11292
11293 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011294 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011295 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011296
Chris Lattner6934a042007-02-11 01:23:03 +000011297 // Move the name to the new instruction first.
11298 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011299
11300 // Insert the new instruction into the basic block...
11301 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011302 BasicBlock::iterator InsertPos = I;
11303
11304 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11305 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11306 ++InsertPos;
11307
11308 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011309
Chris Lattner00d51312004-05-01 23:27:23 +000011310 // Make sure that we reprocess all operands now that we reduced their
11311 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011312 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011313
Chris Lattnerf523d062004-06-09 05:08:07 +000011314 // Instructions can end up on the worklist more than once. Make sure
11315 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011316 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011317
11318 // Erase the old instruction.
11319 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011320 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011321#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011322 DOUT << "IC: Mod = " << OrigI
11323 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011324#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011325
Chris Lattner90ac28c2002-08-02 19:29:35 +000011326 // If the instruction was modified, it's possible that it is now dead.
11327 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011328 if (isInstructionTriviallyDead(I)) {
11329 // Make sure we process all operands now that we are reducing their
11330 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011331 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011332
Chris Lattner00d51312004-05-01 23:27:23 +000011333 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011334 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011335 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011336 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011337 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011338 AddToWorkList(I);
11339 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011340 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011341 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011342 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011343 }
11344 }
11345
Chris Lattnerec9c3582007-03-03 02:04:50 +000011346 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011347
11348 // Do an explicit clear, this shrinks the map if needed.
11349 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011350 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011351}
11352
Chris Lattnerec9c3582007-03-03 02:04:50 +000011353
11354bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011355 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11356
Chris Lattnerec9c3582007-03-03 02:04:50 +000011357 bool EverMadeChange = false;
11358
11359 // Iterate while there is work to do.
11360 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011361 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011362 EverMadeChange = true;
11363 return EverMadeChange;
11364}
11365
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011366FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011367 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011368}
Brian Gaeked0fde302003-11-11 22:41:34 +000011369