blob: ce5f2397d2251bc0d124c5f929ff8e59b68ed1f4 [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 Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000048#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000051#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000052#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000054#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000060#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000061#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000062using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000063using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000070
Chris Lattner0e5f4992006-12-19 21:40:18 +000071namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000072 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000075 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000076 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000078 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000079 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000080 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000081 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000082 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
Chris Lattnerdbab3862007-03-02 21:28:56 +000084 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
89 }
90
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
95
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
98
99 WorklistMap.erase(It);
100 }
101
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
104 Worklist.pop_back();
105 WorklistMap.erase(I);
106 return I;
107 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000108
Chris Lattnerdbab3862007-03-02 21:28:56 +0000109
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000114 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000117 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000118 }
119
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
122 ///
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000126 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000127 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000128
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
132 ///
133 /// Return the specified operand before it is turned into an undef.
134 ///
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
137
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000140 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
143 }
144
145 return R;
146 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000147
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000148 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000149 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000150
151 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000152
Chris Lattner97e52e42002-04-28 21:27:06 +0000153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000154 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000155 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000156 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000157 }
158
Chris Lattner28977af2004-04-05 01:30:19 +0000159 TargetData &getTargetData() const { return *TD; }
160
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
163 // Return Value:
164 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000165 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000166 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000167 //
Chris Lattner7e708292002-06-25 16:13:24 +0000168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000188 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
189 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000190 Instruction *visitFCmpInst(FCmpInst &I);
191 Instruction *visitICmpInst(ICmpInst &I);
192 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000193 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
194 Instruction *LHS,
195 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000196 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
197 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000198
Reid Spencere4d87aa2006-12-23 06:05:41 +0000199 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
200 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000201 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000202 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000203 Instruction *commonCastTransforms(CastInst &CI);
204 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000205 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000206 Instruction *visitTrunc(TruncInst &CI);
207 Instruction *visitZExt(ZExtInst &CI);
208 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000209 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000210 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000211 Instruction *visitFPToUI(FPToUIInst &FI);
212 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000213 Instruction *visitUIToFP(CastInst &CI);
214 Instruction *visitSIToFP(CastInst &CI);
215 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000216 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000217 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000218 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
219 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000220 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000221 Instruction *visitCallInst(CallInst &CI);
222 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000223 Instruction *visitPHINode(PHINode &PN);
224 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000225 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000226 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000227 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000228 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000229 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000230 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000231 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000232 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000233 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000234
235 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000236 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000237
Chris Lattner9fe38862003-06-19 17:00:31 +0000238 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000239 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000240 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000241 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000242 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
243 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000244 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000245
Chris Lattner28977af2004-04-05 01:30:19 +0000246 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000247 // InsertNewInstBefore - insert an instruction New before instruction Old
248 // in the program. Add the new instruction to the worklist.
249 //
Chris Lattner955f3312004-09-28 21:48:02 +0000250 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000251 assert(New && New->getParent() == 0 &&
252 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000253 BasicBlock *BB = Old.getParent();
254 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000255 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000256 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000257 }
258
Chris Lattner0c967662004-09-24 15:21:34 +0000259 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
260 /// This also adds the cast to the worklist. Finally, this returns the
261 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000262 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
263 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000264 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000265
Chris Lattnere2ed0572006-04-06 19:19:17 +0000266 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000267 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000268
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000269 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000270 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000271 return C;
272 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000273
274 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
275 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
276 }
277
Chris Lattner0c967662004-09-24 15:21:34 +0000278
Chris Lattner8b170942002-08-09 23:47:40 +0000279 // ReplaceInstUsesWith - This method is to be used when an instruction is
280 // found to be dead, replacable with another preexisting expression. Here
281 // we add all uses of I to the worklist, replace all uses of I with the new
282 // value, then return I, so that the inst combiner will know that I was
283 // modified.
284 //
285 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000286 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000287 if (&I != V) {
288 I.replaceAllUsesWith(V);
289 return &I;
290 } else {
291 // If we are replacing the instruction with itself, this must be in a
292 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000293 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000294 return &I;
295 }
Chris Lattner8b170942002-08-09 23:47:40 +0000296 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000297
Chris Lattner6dce1a72006-02-07 06:56:34 +0000298 // UpdateValueUsesWith - This method is to be used when an value is
299 // found to be replacable with another preexisting expression or was
300 // updated. Here we add all uses of I to the worklist, replace all uses of
301 // I with the new value (unless the instruction was just updated), then
302 // return true, so that the inst combiner will know that I was modified.
303 //
304 bool UpdateValueUsesWith(Value *Old, Value *New) {
305 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
306 if (Old != New)
307 Old->replaceAllUsesWith(New);
308 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000309 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000310 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000311 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000312 return true;
313 }
314
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000315 // EraseInstFromFunction - When dealing with an instruction that has side
316 // effects or produces a void value, we can't rely on DCE to delete the
317 // instruction. Instead, visit methods should return the value returned by
318 // this function.
319 Instruction *EraseInstFromFunction(Instruction &I) {
320 assert(I.use_empty() && "Cannot erase instruction that is used!");
321 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000322 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000323 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000324 return 0; // Don't do anything with FI
325 }
326
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000327 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000328 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
329 /// InsertBefore instruction. This is specialized a bit to avoid inserting
330 /// casts that are known to not do anything...
331 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000332 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
333 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000334 Instruction *InsertBefore);
335
Reid Spencere4d87aa2006-12-23 06:05:41 +0000336 /// SimplifyCommutative - This performs a few simplifications for
337 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000338 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000339
Reid Spencere4d87aa2006-12-23 06:05:41 +0000340 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
341 /// most-complex to least-complex order.
342 bool SimplifyCompare(CmpInst &I);
343
Reid Spencer2ec619a2007-03-23 21:24:59 +0000344 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
345 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000346 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
347 APInt& KnownZero, APInt& KnownOne,
348 unsigned Depth = 0);
349
Chris Lattner867b99f2006-10-05 06:55:50 +0000350 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
351 uint64_t &UndefElts, unsigned Depth = 0);
352
Chris Lattner4e998b22004-09-29 05:07:12 +0000353 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
354 // PHI node as operand #0, see if we can fold the instruction into the PHI
355 // (which is only possible if all operands to the PHI are constants).
356 Instruction *FoldOpIntoPhi(Instruction &I);
357
Chris Lattnerbac32862004-11-14 19:13:23 +0000358 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
359 // operator and they all are only used by the PHI, PHI together their
360 // inputs, and do the operation once, to the result of the PHI.
361 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000362 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
363
364
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000365 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
366 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000367
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000368 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000369 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000370 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000371 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000372 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000373 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000374 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000375 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000376 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000377
Chris Lattnerafe91a52006-06-15 19:07:26 +0000378
Reid Spencerc55b2432006-12-13 18:21:21 +0000379 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000380
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000381 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Dan Gohman45b4e482008-05-19 22:14:15 +0000382 APInt& KnownOne, unsigned Depth = 0) const;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000383 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
Dan Gohman45b4e482008-05-19 22:14:15 +0000384 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000385 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
386 unsigned CastOpc,
387 int &NumCastsRemoved);
388 unsigned GetOrEnforceKnownAlignment(Value *V,
389 unsigned PrefAlign = 0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000390 };
391}
392
Dan Gohman844731a2008-05-13 00:00:25 +0000393char InstCombiner::ID = 0;
394static RegisterPass<InstCombiner>
395X("instcombine", "Combine redundant instructions");
396
Chris Lattner4f98c562003-03-10 21:43:22 +0000397// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000398// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000399static unsigned getComplexity(Value *V) {
400 if (isa<Instruction>(V)) {
401 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000402 return 3;
403 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000404 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000405 if (isa<Argument>(V)) return 3;
406 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000407}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000408
Chris Lattnerc8802d22003-03-11 00:12:48 +0000409// isOnlyUse - Return true if this instruction will be deleted if we stop using
410// it.
411static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000412 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000413}
414
Chris Lattner4cb170c2004-02-23 06:38:22 +0000415// getPromotedType - Return the specified type promoted as it would be to pass
416// though a va_arg area...
417static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000418 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
419 if (ITy->getBitWidth() < 32)
420 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000421 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000422 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000423}
424
Reid Spencer3da59db2006-11-27 01:05:10 +0000425/// getBitCastOperand - If the specified operand is a CastInst or a constant
426/// expression bitcast, return the operand value, otherwise return null.
427static Value *getBitCastOperand(Value *V) {
428 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000429 return I->getOperand(0);
430 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000431 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000432 return CE->getOperand(0);
433 return 0;
434}
435
Reid Spencer3da59db2006-11-27 01:05:10 +0000436/// This function is a wrapper around CastInst::isEliminableCastPair. It
437/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000438static Instruction::CastOps
439isEliminableCastPair(
440 const CastInst *CI, ///< The first cast instruction
441 unsigned opcode, ///< The opcode of the second cast instruction
442 const Type *DstTy, ///< The target type for the second cast instruction
443 TargetData *TD ///< The target data for pointer size
444) {
445
446 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
447 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000448
Reid Spencer3da59db2006-11-27 01:05:10 +0000449 // Get the opcodes of the two Cast instructions
450 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
451 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000452
Reid Spencer3da59db2006-11-27 01:05:10 +0000453 return Instruction::CastOps(
454 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
455 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000456}
457
458/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
459/// in any code being generated. It does not require codegen if V is simple
460/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000461static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
462 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000463 if (V->getType() == Ty || isa<Constant>(V)) return false;
464
Chris Lattner01575b72006-05-25 23:24:33 +0000465 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000466 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000467 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000468 return false;
469 return true;
470}
471
472/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
473/// InsertBefore instruction. This is specialized a bit to avoid inserting
474/// casts that are known to not do anything...
475///
Reid Spencer17212df2006-12-12 09:18:51 +0000476Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
477 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000478 Instruction *InsertBefore) {
479 if (V->getType() == DestTy) return V;
480 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000481 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000482
Reid Spencer17212df2006-12-12 09:18:51 +0000483 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000484}
485
Chris Lattner4f98c562003-03-10 21:43:22 +0000486// SimplifyCommutative - This performs a few simplifications for commutative
487// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000488//
Chris Lattner4f98c562003-03-10 21:43:22 +0000489// 1. Order operands such that they are listed from right (least complex) to
490// left (most complex). This puts constants before unary operators before
491// binary operators.
492//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000493// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
494// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000495//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000496bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000497 bool Changed = false;
498 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
499 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000500
Chris Lattner4f98c562003-03-10 21:43:22 +0000501 if (!I.isAssociative()) return Changed;
502 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000503 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
504 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
505 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000506 Constant *Folded = ConstantExpr::get(I.getOpcode(),
507 cast<Constant>(I.getOperand(1)),
508 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000509 I.setOperand(0, Op->getOperand(0));
510 I.setOperand(1, Folded);
511 return true;
512 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
513 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
514 isOnlyUse(Op) && isOnlyUse(Op1)) {
515 Constant *C1 = cast<Constant>(Op->getOperand(1));
516 Constant *C2 = cast<Constant>(Op1->getOperand(1));
517
518 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000519 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000520 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521 Op1->getOperand(0),
522 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000523 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000524 I.setOperand(0, New);
525 I.setOperand(1, Folded);
526 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000527 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000528 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000529 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000530}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000531
Reid Spencere4d87aa2006-12-23 06:05:41 +0000532/// SimplifyCompare - For a CmpInst this function just orders the operands
533/// so that theyare listed from right (least complex) to left (most complex).
534/// This puts constants before unary operators before binary operators.
535bool InstCombiner::SimplifyCompare(CmpInst &I) {
536 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
537 return false;
538 I.swapOperands();
539 // Compare instructions are not associative so there's nothing else we can do.
540 return true;
541}
542
Chris Lattner8d969642003-03-10 23:06:50 +0000543// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
544// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000545//
Chris Lattner8d969642003-03-10 23:06:50 +0000546static inline Value *dyn_castNegVal(Value *V) {
547 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000548 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000549
Chris Lattner0ce85802004-12-14 20:08:06 +0000550 // Constants can be considered to be negated values if they can be folded.
551 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
552 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000553 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000554}
555
Chris Lattner8d969642003-03-10 23:06:50 +0000556static inline Value *dyn_castNotVal(Value *V) {
557 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000558 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000559
560 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000561 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000562 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000563 return 0;
564}
565
Chris Lattnerc8802d22003-03-11 00:12:48 +0000566// dyn_castFoldableMul - If this value is a multiply that can be folded into
567// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000568// non-constant operand of the multiply, and set CST to point to the multiplier.
569// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000570//
Chris Lattner50af16a2004-11-13 19:50:12 +0000571static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000572 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000573 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000574 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000575 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000576 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000577 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000578 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000579 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000580 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000581 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000582 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000583 return I->getOperand(0);
584 }
585 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000586 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000587}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000588
Chris Lattner574da9b2005-01-13 20:14:25 +0000589/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
590/// expression, return it.
591static User *dyn_castGetElementPtr(Value *V) {
592 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
593 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
594 if (CE->getOpcode() == Instruction::GetElementPtr)
595 return cast<User>(V);
596 return false;
597}
598
Dan Gohmaneee962e2008-04-10 18:43:06 +0000599/// getOpcode - If this is an Instruction or a ConstantExpr, return the
600/// opcode value. Otherwise return UserOp1.
Dan Gohman45b4e482008-05-19 22:14:15 +0000601static unsigned getOpcode(Value *V) {
602 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000603 return I->getOpcode();
Dan Gohman45b4e482008-05-19 22:14:15 +0000604 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000605 return CE->getOpcode();
606 // Use UserOp1 to mean there's no opcode.
607 return Instruction::UserOp1;
608}
609
Reid Spencer7177c3a2007-03-25 05:33:51 +0000610/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000611static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000612 APInt Val(C->getValue());
613 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000614}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000615/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000616static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000617 APInt Val(C->getValue());
618 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000619}
620/// Add - Add two ConstantInts together
621static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
622 return ConstantInt::get(C1->getValue() + C2->getValue());
623}
624/// And - Bitwise AND two ConstantInts together
625static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
626 return ConstantInt::get(C1->getValue() & C2->getValue());
627}
628/// Subtract - Subtract one ConstantInt from another
629static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
630 return ConstantInt::get(C1->getValue() - C2->getValue());
631}
632/// Multiply - Multiply two ConstantInts together
633static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
634 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000635}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000636/// MultiplyOverflows - True if the multiply can not be expressed in an int
637/// this size.
638static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
639 uint32_t W = C1->getBitWidth();
640 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
641 if (sign) {
642 LHSExt.sext(W * 2);
643 RHSExt.sext(W * 2);
644 } else {
645 LHSExt.zext(W * 2);
646 RHSExt.zext(W * 2);
647 }
648
649 APInt MulExt = LHSExt * RHSExt;
650
651 if (sign) {
652 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
653 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
654 return MulExt.slt(Min) || MulExt.sgt(Max);
655 } else
656 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
657}
Chris Lattner955f3312004-09-28 21:48:02 +0000658
Chris Lattner68d5ff22006-02-09 07:38:58 +0000659/// ComputeMaskedBits - Determine which of the bits specified in Mask are
660/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000661/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
662/// processing.
663/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
664/// we cannot optimize based on the assumption that it is zero without changing
665/// it to be an explicit zero. If we don't change it to zero, other code could
666/// optimized based on the contradictory assumption that it is non-zero.
667/// Because instcombine aggressively folds operations with undef args anyway,
668/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000669void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
670 APInt& KnownZero, APInt& KnownOne,
Dan Gohman45b4e482008-05-19 22:14:15 +0000671 unsigned Depth) const {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000672 assert(V && "No Value?");
673 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000674 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000675 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
676 "Not integer or pointer type!");
677 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
678 (!isa<IntegerType>(V->getType()) ||
679 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000680 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000681 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000682 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Dan Gohman45b4e482008-05-19 22:14:15 +0000683
Reid Spencer3e7594f2007-03-08 01:46:38 +0000684 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
685 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000686 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000687 KnownZero = ~KnownOne & Mask;
688 return;
689 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000690 // Null is all-zeros.
691 if (isa<ConstantPointerNull>(V)) {
692 KnownOne.clear();
693 KnownZero = Mask;
694 return;
695 }
696 // The address of an aligned GlobalValue has trailing zeros.
697 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
698 unsigned Align = GV->getAlignment();
699 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
700 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
701 if (Align > 0)
702 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
703 CountTrailingZeros_32(Align));
704 else
705 KnownZero.clear();
706 KnownOne.clear();
707 return;
708 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000709
Dan Gohman23e8b712008-04-28 17:02:21 +0000710 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
711
Reid Spencer3e7594f2007-03-08 01:46:38 +0000712 if (Depth == 6 || Mask == 0)
713 return; // Limit search depth.
714
Dan Gohmaneee962e2008-04-10 18:43:06 +0000715 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000716 if (!I) return;
717
718 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000719 switch (getOpcode(I)) {
720 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000721 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000722 // If either the LHS or the RHS are Zero, the result is zero.
723 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000724 APInt Mask2(Mask & ~KnownZero);
725 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000726 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
727 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
728
729 // Output known-1 bits are only known if set in both the LHS & RHS.
730 KnownOne &= KnownOne2;
731 // Output known-0 are known to be clear if zero in either the LHS | RHS.
732 KnownZero |= KnownZero2;
733 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000734 }
735 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000736 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000737 APInt Mask2(Mask & ~KnownOne);
738 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000739 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
740 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
741
742 // Output known-0 bits are only known if clear in both the LHS & RHS.
743 KnownZero &= KnownZero2;
744 // Output known-1 are known to be set if set in either the LHS | RHS.
745 KnownOne |= KnownOne2;
746 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000747 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000748 case Instruction::Xor: {
749 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
750 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
751 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
752 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
753
754 // Output known-0 bits are known if clear or set in both the LHS & RHS.
755 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
756 // Output known-1 are known to be set if set in only one of the LHS, RHS.
757 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
758 KnownZero = KnownZeroOut;
759 return;
760 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000761 case Instruction::Mul: {
762 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
763 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
764 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
765 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
766 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
767
768 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman23e8b712008-04-28 17:02:21 +0000769 // Also compute a conserative estimate for high known-0 bits.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000770 // More trickiness is possible, but this is sufficient for the
771 // interesting case of alignment computation.
772 KnownOne.clear();
773 unsigned TrailZ = KnownZero.countTrailingOnes() +
774 KnownZero2.countTrailingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +0000775 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman42ac9292008-05-07 00:35:55 +0000776 KnownZero2.countLeadingOnes(),
777 BitWidth) - BitWidth;
Dan Gohman23e8b712008-04-28 17:02:21 +0000778
Dan Gohmaneee962e2008-04-10 18:43:06 +0000779 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000780 LeadZ = std::min(LeadZ, BitWidth);
781 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
782 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000783 KnownZero &= Mask;
784 return;
785 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000786 case Instruction::UDiv: {
787 // For the purposes of computing leading zeros we can conservatively
788 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1d9cd502008-05-02 21:30:02 +0000789 // be less than the denominator.
Dan Gohman23e8b712008-04-28 17:02:21 +0000790 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
791 ComputeMaskedBits(I->getOperand(0),
792 AllOnes, KnownZero2, KnownOne2, Depth+1);
793 unsigned LeadZ = KnownZero2.countLeadingOnes();
794
795 KnownOne2.clear();
796 KnownZero2.clear();
797 ComputeMaskedBits(I->getOperand(1),
798 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1d9cd502008-05-02 21:30:02 +0000799 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
800 if (RHSUnknownLeadingOnes != BitWidth)
801 LeadZ = std::min(BitWidth,
802 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000803
804 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
805 return;
806 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000807 case Instruction::Select:
808 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
809 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
810 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
811 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
812
813 // Only known if known in both the LHS and RHS.
814 KnownOne &= KnownOne2;
815 KnownZero &= KnownZero2;
816 return;
817 case Instruction::FPTrunc:
818 case Instruction::FPExt:
819 case Instruction::FPToUI:
820 case Instruction::FPToSI:
821 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000822 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000823 return; // Can't work with floating point.
824 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000825 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000826 // We can't handle these if we don't know the pointer size.
827 if (!TD) return;
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000828 // FALL THROUGH and handle them the same as zext/trunc.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000829 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000830 case Instruction::Trunc: {
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000831 // Note that we handle pointer operands here because of inttoptr/ptrtoint
832 // which fall through here.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000833 const Type *SrcTy = I->getOperand(0)->getType();
834 uint32_t SrcBitWidth = TD ?
835 TD->getTypeSizeInBits(SrcTy) :
836 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000837 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000838 MaskIn.zextOrTrunc(SrcBitWidth);
839 KnownZero.zextOrTrunc(SrcBitWidth);
840 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000841 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000842 KnownZero.zextOrTrunc(BitWidth);
843 KnownOne.zextOrTrunc(BitWidth);
844 // Any top bits are known to be zero.
845 if (BitWidth > SrcBitWidth)
846 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000847 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000848 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000849 case Instruction::BitCast: {
850 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000851 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000852 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
853 return;
854 }
855 break;
856 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000857 case Instruction::SExt: {
858 // Compute the bits in the result that are not present in the input.
859 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000860 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000861
Zhou Shengaa305ab2007-03-28 02:19:03 +0000862 APInt MaskIn(Mask);
863 MaskIn.trunc(SrcBitWidth);
864 KnownZero.trunc(SrcBitWidth);
865 KnownOne.trunc(SrcBitWidth);
866 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000867 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000868 KnownZero.zext(BitWidth);
869 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000870
871 // If the sign bit of the input is known set or clear, then we know the
872 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000873 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000874 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000875 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000876 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000877 return;
878 }
879 case Instruction::Shl:
880 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
881 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000882 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000883 APInt Mask2(Mask.lshr(ShiftAmt));
884 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000885 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000886 KnownZero <<= ShiftAmt;
887 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000888 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000889 return;
890 }
891 break;
892 case Instruction::LShr:
893 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
894 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
895 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000896 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000897
898 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000899 APInt Mask2(Mask.shl(ShiftAmt));
900 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000901 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
902 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
903 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000904 // high bits known zero.
905 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000906 return;
907 }
908 break;
909 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000910 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000911 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
912 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000913 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000914
915 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000916 APInt Mask2(Mask.shl(ShiftAmt));
917 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000918 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
919 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
920 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
921
Zhou Shengaa305ab2007-03-28 02:19:03 +0000922 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
923 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000924 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000925 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000926 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000927 return;
928 }
929 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000930 case Instruction::Sub: {
931 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
932 // We know that the top bits of C-X are clear if X contains less bits
933 // than C (i.e. no wrap-around can happen). For example, 20-X is
934 // positive if we can prove that X is >= 0 and < 16.
935 if (!CLHS->getValue().isNegative()) {
936 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
937 // NLZ can't be BitWidth with no sign bit
938 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000939 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
940 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000941
Dan Gohman23e8b712008-04-28 17:02:21 +0000942 // If all of the MaskV bits are known to be zero, then we know the
943 // output top bits are zero, because we now know that the output is
944 // from [0-C].
945 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000946 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
947 // Top bits known zero.
948 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000949 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000950 }
951 }
952 }
953 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000954 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000955 // Output known-0 bits are known if clear or set in both the low clear bits
956 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
957 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000958 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
959 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
960 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
961 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
962
963 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
964 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
965 KnownZeroOut = std::min(KnownZeroOut,
966 KnownZero2.countTrailingOnes());
967
968 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000969 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000970 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000971 case Instruction::SRem:
972 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
973 APInt RA = Rem->getValue();
974 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000975 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000976 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
977 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
978
979 // The sign of a remainder is equal to the sign of the first
980 // operand (zero being positive).
981 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
982 KnownZero2 |= ~LowBits;
983 else if (KnownOne2[BitWidth-1])
984 KnownOne2 |= ~LowBits;
985
986 KnownZero |= KnownZero2 & Mask;
987 KnownOne |= KnownOne2 & Mask;
988
989 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
990 }
991 }
992 break;
Dan Gohman23e8b712008-04-28 17:02:21 +0000993 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000994 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
995 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +0000996 if (RA.isPowerOf2()) {
997 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000998 APInt Mask2 = LowBits & Mask;
999 KnownZero |= ~LowBits & Mask;
1000 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1001 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001002 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001003 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001004 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001005
1006 // Since the result is less than or equal to either operand, any leading
1007 // zero bits in either operand must also exist in the result.
1008 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1009 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1010 Depth+1);
1011 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1012 Depth+1);
1013
1014 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1015 KnownZero2.countLeadingOnes());
1016 KnownOne.clear();
1017 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001018 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001019 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001020
1021 case Instruction::Alloca:
1022 case Instruction::Malloc: {
1023 AllocationInst *AI = cast<AllocationInst>(V);
1024 unsigned Align = AI->getAlignment();
1025 if (Align == 0 && TD) {
1026 if (isa<AllocaInst>(AI))
1027 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1028 else if (isa<MallocInst>(AI)) {
1029 // Malloc returns maximally aligned memory.
1030 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1031 Align =
1032 std::max(Align,
1033 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1034 Align =
1035 std::max(Align,
1036 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1037 }
1038 }
1039
1040 if (Align > 0)
1041 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1042 CountTrailingZeros_32(Align));
1043 break;
1044 }
1045 case Instruction::GetElementPtr: {
1046 // Analyze all of the subscripts of this getelementptr instruction
1047 // to determine if we can prove known low zero bits.
1048 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1049 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1050 ComputeMaskedBits(I->getOperand(0), LocalMask,
1051 LocalKnownZero, LocalKnownOne, Depth+1);
1052 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1053
1054 gep_type_iterator GTI = gep_type_begin(I);
1055 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1056 Value *Index = I->getOperand(i);
1057 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1058 // Handle struct member offset arithmetic.
1059 if (!TD) return;
1060 const StructLayout *SL = TD->getStructLayout(STy);
1061 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1062 uint64_t Offset = SL->getElementOffset(Idx);
1063 TrailZ = std::min(TrailZ,
1064 CountTrailingZeros_64(Offset));
1065 } else {
1066 // Handle array index arithmetic.
1067 const Type *IndexedTy = GTI.getIndexedType();
1068 if (!IndexedTy->isSized()) return;
1069 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1070 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1071 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1072 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1073 ComputeMaskedBits(Index, LocalMask,
1074 LocalKnownZero, LocalKnownOne, Depth+1);
1075 TrailZ = std::min(TrailZ,
1076 CountTrailingZeros_64(TypeSize) +
1077 LocalKnownZero.countTrailingOnes());
1078 }
1079 }
1080
1081 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1082 break;
1083 }
1084 case Instruction::PHI: {
1085 PHINode *P = cast<PHINode>(I);
1086 // Handle the case of a simple two-predecessor recurrence PHI.
1087 // There's a lot more that could theoretically be done here, but
1088 // this is sufficient to catch some interesting cases.
1089 if (P->getNumIncomingValues() == 2) {
1090 for (unsigned i = 0; i != 2; ++i) {
1091 Value *L = P->getIncomingValue(i);
1092 Value *R = P->getIncomingValue(!i);
1093 User *LU = dyn_cast<User>(L);
1094 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1095 // Check for operations that have the property that if
1096 // both their operands have low zero bits, the result
1097 // will have low zero bits.
1098 if (Opcode == Instruction::Add ||
1099 Opcode == Instruction::Sub ||
1100 Opcode == Instruction::And ||
1101 Opcode == Instruction::Or ||
1102 Opcode == Instruction::Mul) {
1103 Value *LL = LU->getOperand(0);
1104 Value *LR = LU->getOperand(1);
1105 // Find a recurrence.
1106 if (LL == I)
1107 L = LR;
1108 else if (LR == I)
1109 L = LL;
1110 else
1111 break;
1112 // Ok, we have a PHI of the form L op= R. Check for low
1113 // zero bits.
1114 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1115 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1116 Mask2 = APInt::getLowBitsSet(BitWidth,
1117 KnownZero2.countTrailingOnes());
1118 KnownOne2.clear();
1119 KnownZero2.clear();
1120 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1121 KnownZero = Mask &
1122 APInt::getLowBitsSet(BitWidth,
1123 KnownZero2.countTrailingOnes());
1124 break;
1125 }
1126 }
1127 }
1128 break;
1129 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001130 case Instruction::Call:
1131 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1132 switch (II->getIntrinsicID()) {
1133 default: break;
1134 case Intrinsic::ctpop:
1135 case Intrinsic::ctlz:
1136 case Intrinsic::cttz: {
1137 unsigned LowBits = Log2_32(BitWidth)+1;
1138 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1139 break;
1140 }
1141 }
1142 }
1143 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001144 }
1145}
1146
Reid Spencere7816b52007-03-08 01:52:58 +00001147/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1148/// this predicate to simplify operations downstream. Mask is known to be zero
1149/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001150bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1151 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001152 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001153 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1154 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1155 return (KnownZero & Mask) == Mask;
1156}
1157
Chris Lattner255d8912006-02-11 09:31:47 +00001158/// ShrinkDemandedConstant - Check to see if the specified operand of the
1159/// specified instruction is a constant integer. If so, check to see if there
1160/// are any bits set in the constant that are not demanded. If so, shrink the
1161/// constant and return true.
1162static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001163 APInt Demanded) {
1164 assert(I && "No instruction?");
1165 assert(OpNo < I->getNumOperands() && "Operand index too large");
1166
1167 // If the operand is not a constant integer, nothing to do.
1168 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1169 if (!OpC) return false;
1170
1171 // If there are no bits set that aren't demanded, nothing to do.
1172 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1173 if ((~Demanded & OpC->getValue()) == 0)
1174 return false;
1175
1176 // This instruction is producing bits that are not demanded. Shrink the RHS.
1177 Demanded &= OpC->getValue();
1178 I->setOperand(OpNo, ConstantInt::get(Demanded));
1179 return true;
1180}
1181
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001182// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1183// set of known zero and one bits, compute the maximum and minimum values that
1184// could have the specified known zero and known one bits, returning them in
1185// min/max.
1186static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001187 const APInt& KnownZero,
1188 const APInt& KnownOne,
1189 APInt& Min, APInt& Max) {
1190 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1191 assert(KnownZero.getBitWidth() == BitWidth &&
1192 KnownOne.getBitWidth() == BitWidth &&
1193 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1194 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001195 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001196
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001197 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1198 // bit if it is unknown.
1199 Min = KnownOne;
1200 Max = KnownOne|UnknownBits;
1201
Zhou Sheng4acf1552007-03-28 05:15:57 +00001202 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001203 Min.set(BitWidth-1);
1204 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001205 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001206}
1207
1208// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1209// a set of known zero and one bits, compute the maximum and minimum values that
1210// could have the specified known zero and known one bits, returning them in
1211// min/max.
1212static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001213 const APInt &KnownZero,
1214 const APInt &KnownOne,
1215 APInt &Min, APInt &Max) {
1216 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001217 assert(KnownZero.getBitWidth() == BitWidth &&
1218 KnownOne.getBitWidth() == BitWidth &&
1219 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1220 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001221 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001222
1223 // The minimum value is when the unknown bits are all zeros.
1224 Min = KnownOne;
1225 // The maximum value is when the unknown bits are all ones.
1226 Max = KnownOne|UnknownBits;
1227}
Chris Lattner255d8912006-02-11 09:31:47 +00001228
Reid Spencer8cb68342007-03-12 17:25:59 +00001229/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1230/// value based on the demanded bits. When this function is called, it is known
1231/// that only the bits set in DemandedMask of the result of V are ever used
1232/// downstream. Consequently, depending on the mask and V, it may be possible
1233/// to replace V with a constant or one of its operands. In such cases, this
1234/// function does the replacement and returns true. In all other cases, it
1235/// returns false after analyzing the expression and setting KnownOne and known
1236/// to be one in the expression. KnownZero contains all the bits that are known
1237/// to be zero in the expression. These are provided to potentially allow the
1238/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1239/// the expression. KnownOne and KnownZero always follow the invariant that
1240/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1241/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1242/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1243/// and KnownOne must all be the same.
1244bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1245 APInt& KnownZero, APInt& KnownOne,
1246 unsigned Depth) {
1247 assert(V != 0 && "Null pointer of Value???");
1248 assert(Depth <= 6 && "Limit Search Depth");
1249 uint32_t BitWidth = DemandedMask.getBitWidth();
1250 const IntegerType *VTy = cast<IntegerType>(V->getType());
1251 assert(VTy->getBitWidth() == BitWidth &&
1252 KnownZero.getBitWidth() == BitWidth &&
1253 KnownOne.getBitWidth() == BitWidth &&
1254 "Value *V, DemandedMask, KnownZero and KnownOne \
1255 must have same BitWidth");
1256 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1257 // We know all of the bits for a constant!
1258 KnownOne = CI->getValue() & DemandedMask;
1259 KnownZero = ~KnownOne & DemandedMask;
1260 return false;
1261 }
1262
Zhou Sheng96704452007-03-14 03:21:24 +00001263 KnownZero.clear();
1264 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 if (!V->hasOneUse()) { // Other users may use these bits.
1266 if (Depth != 0) { // Not at the root.
1267 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1268 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1269 return false;
1270 }
1271 // If this is the root being simplified, allow it to have multiple uses,
1272 // just set the DemandedMask to all bits.
1273 DemandedMask = APInt::getAllOnesValue(BitWidth);
1274 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1275 if (V != UndefValue::get(VTy))
1276 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1277 return false;
1278 } else if (Depth == 6) { // Limit search depth.
1279 return false;
1280 }
1281
1282 Instruction *I = dyn_cast<Instruction>(V);
1283 if (!I) return false; // Only analyze instructions.
1284
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1286 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1287 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001288 default:
1289 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1290 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001291 case Instruction::And:
1292 // If either the LHS or the RHS are Zero, the result is zero.
1293 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1294 RHSKnownZero, RHSKnownOne, Depth+1))
1295 return true;
1296 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1297 "Bits known to be one AND zero?");
1298
1299 // If something is known zero on the RHS, the bits aren't demanded on the
1300 // LHS.
1301 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1302 LHSKnownZero, LHSKnownOne, Depth+1))
1303 return true;
1304 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1305 "Bits known to be one AND zero?");
1306
1307 // If all of the demanded bits are known 1 on one side, return the other.
1308 // These bits cannot contribute to the result of the 'and'.
1309 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1310 (DemandedMask & ~LHSKnownZero))
1311 return UpdateValueUsesWith(I, I->getOperand(0));
1312 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1313 (DemandedMask & ~RHSKnownZero))
1314 return UpdateValueUsesWith(I, I->getOperand(1));
1315
1316 // If all of the demanded bits in the inputs are known zeros, return zero.
1317 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1318 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1319
1320 // If the RHS is a constant, see if we can simplify it.
1321 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1322 return UpdateValueUsesWith(I, I);
1323
1324 // Output known-1 bits are only known if set in both the LHS & RHS.
1325 RHSKnownOne &= LHSKnownOne;
1326 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1327 RHSKnownZero |= LHSKnownZero;
1328 break;
1329 case Instruction::Or:
1330 // If either the LHS or the RHS are One, the result is One.
1331 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1332 RHSKnownZero, RHSKnownOne, Depth+1))
1333 return true;
1334 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1335 "Bits known to be one AND zero?");
1336 // If something is known one on the RHS, the bits aren't demanded on the
1337 // LHS.
1338 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1339 LHSKnownZero, LHSKnownOne, Depth+1))
1340 return true;
1341 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1342 "Bits known to be one AND zero?");
1343
1344 // If all of the demanded bits are known zero on one side, return the other.
1345 // These bits cannot contribute to the result of the 'or'.
1346 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1347 (DemandedMask & ~LHSKnownOne))
1348 return UpdateValueUsesWith(I, I->getOperand(0));
1349 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1350 (DemandedMask & ~RHSKnownOne))
1351 return UpdateValueUsesWith(I, I->getOperand(1));
1352
1353 // If all of the potentially set bits on one side are known to be set on
1354 // the other side, just use the 'other' side.
1355 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1356 (DemandedMask & (~RHSKnownZero)))
1357 return UpdateValueUsesWith(I, I->getOperand(0));
1358 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1359 (DemandedMask & (~LHSKnownZero)))
1360 return UpdateValueUsesWith(I, I->getOperand(1));
1361
1362 // If the RHS is a constant, see if we can simplify it.
1363 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1364 return UpdateValueUsesWith(I, I);
1365
1366 // Output known-0 bits are only known if clear in both the LHS & RHS.
1367 RHSKnownZero &= LHSKnownZero;
1368 // Output known-1 are known to be set if set in either the LHS | RHS.
1369 RHSKnownOne |= LHSKnownOne;
1370 break;
1371 case Instruction::Xor: {
1372 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1373 RHSKnownZero, RHSKnownOne, Depth+1))
1374 return true;
1375 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1376 "Bits known to be one AND zero?");
1377 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1378 LHSKnownZero, LHSKnownOne, Depth+1))
1379 return true;
1380 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1381 "Bits known to be one AND zero?");
1382
1383 // If all of the demanded bits are known zero on one side, return the other.
1384 // These bits cannot contribute to the result of the 'xor'.
1385 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1386 return UpdateValueUsesWith(I, I->getOperand(0));
1387 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1388 return UpdateValueUsesWith(I, I->getOperand(1));
1389
1390 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1391 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1392 (RHSKnownOne & LHSKnownOne);
1393 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1394 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1395 (RHSKnownOne & LHSKnownZero);
1396
1397 // If all of the demanded bits are known to be zero on one side or the
1398 // other, turn this into an *inclusive* or.
1399 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1400 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1401 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001402 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001403 I->getName());
1404 InsertNewInstBefore(Or, *I);
1405 return UpdateValueUsesWith(I, Or);
1406 }
1407
1408 // If all of the demanded bits on one side are known, and all of the set
1409 // bits on that side are also known to be set on the other side, turn this
1410 // into an AND, as we know the bits will be cleared.
1411 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1412 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1413 // all known
1414 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1415 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1416 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001417 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +00001418 InsertNewInstBefore(And, *I);
1419 return UpdateValueUsesWith(I, And);
1420 }
1421 }
1422
1423 // If the RHS is a constant, see if we can simplify it.
1424 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1425 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1426 return UpdateValueUsesWith(I, I);
1427
1428 RHSKnownZero = KnownZeroOut;
1429 RHSKnownOne = KnownOneOut;
1430 break;
1431 }
1432 case Instruction::Select:
1433 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1434 RHSKnownZero, RHSKnownOne, Depth+1))
1435 return true;
1436 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1437 LHSKnownZero, LHSKnownOne, Depth+1))
1438 return true;
1439 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1440 "Bits known to be one AND zero?");
1441 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1442 "Bits known to be one AND zero?");
1443
1444 // If the operands are constants, see if we can simplify them.
1445 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1446 return UpdateValueUsesWith(I, I);
1447 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1448 return UpdateValueUsesWith(I, I);
1449
1450 // Only known if known in both the LHS and RHS.
1451 RHSKnownOne &= LHSKnownOne;
1452 RHSKnownZero &= LHSKnownZero;
1453 break;
1454 case Instruction::Trunc: {
1455 uint32_t truncBf =
1456 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001457 DemandedMask.zext(truncBf);
1458 RHSKnownZero.zext(truncBf);
1459 RHSKnownOne.zext(truncBf);
1460 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1461 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001462 return true;
1463 DemandedMask.trunc(BitWidth);
1464 RHSKnownZero.trunc(BitWidth);
1465 RHSKnownOne.trunc(BitWidth);
1466 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1467 "Bits known to be one AND zero?");
1468 break;
1469 }
1470 case Instruction::BitCast:
1471 if (!I->getOperand(0)->getType()->isInteger())
1472 return false;
1473
1474 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1475 RHSKnownZero, RHSKnownOne, Depth+1))
1476 return true;
1477 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1478 "Bits known to be one AND zero?");
1479 break;
1480 case Instruction::ZExt: {
1481 // Compute the bits in the result that are not present in the input.
1482 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001483 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001484
Zhou Shengd48653a2007-03-29 04:45:55 +00001485 DemandedMask.trunc(SrcBitWidth);
1486 RHSKnownZero.trunc(SrcBitWidth);
1487 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001488 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1489 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001490 return true;
1491 DemandedMask.zext(BitWidth);
1492 RHSKnownZero.zext(BitWidth);
1493 RHSKnownOne.zext(BitWidth);
1494 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1495 "Bits known to be one AND zero?");
1496 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001497 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001498 break;
1499 }
1500 case Instruction::SExt: {
1501 // Compute the bits in the result that are not present in the input.
1502 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001503 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001504
Reid Spencer8cb68342007-03-12 17:25:59 +00001505 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001506 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001507
Zhou Sheng01542f32007-03-29 02:26:30 +00001508 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001509 // If any of the sign extended bits are demanded, we know that the sign
1510 // bit is demanded.
1511 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001512 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001513
Zhou Shengd48653a2007-03-29 04:45:55 +00001514 InputDemandedBits.trunc(SrcBitWidth);
1515 RHSKnownZero.trunc(SrcBitWidth);
1516 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001517 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1518 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001519 return true;
1520 InputDemandedBits.zext(BitWidth);
1521 RHSKnownZero.zext(BitWidth);
1522 RHSKnownOne.zext(BitWidth);
1523 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1524 "Bits known to be one AND zero?");
1525
1526 // If the sign bit of the input is known set or clear, then we know the
1527 // top bits of the result.
1528
1529 // If the input sign bit is known zero, or if the NewBits are not demanded
1530 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001531 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001532 {
1533 // Convert to ZExt cast
1534 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1535 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001536 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001537 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001538 }
1539 break;
1540 }
1541 case Instruction::Add: {
1542 // Figure out what the input bits are. If the top bits of the and result
1543 // are not demanded, then the add doesn't demand them from its input
1544 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001545 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001546
1547 // If there is a constant on the RHS, there are a variety of xformations
1548 // we can do.
1549 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1550 // If null, this should be simplified elsewhere. Some of the xforms here
1551 // won't work if the RHS is zero.
1552 if (RHS->isZero())
1553 break;
1554
1555 // If the top bit of the output is demanded, demand everything from the
1556 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001557 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001558
1559 // Find information about known zero/one bits in the input.
1560 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1561 LHSKnownZero, LHSKnownOne, Depth+1))
1562 return true;
1563
1564 // If the RHS of the add has bits set that can't affect the input, reduce
1565 // the constant.
1566 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1567 return UpdateValueUsesWith(I, I);
1568
1569 // Avoid excess work.
1570 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1571 break;
1572
1573 // Turn it into OR if input bits are zero.
1574 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1575 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001576 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001577 I->getName());
1578 InsertNewInstBefore(Or, *I);
1579 return UpdateValueUsesWith(I, Or);
1580 }
1581
1582 // We can say something about the output known-zero and known-one bits,
1583 // depending on potential carries from the input constant and the
1584 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1585 // bits set and the RHS constant is 0x01001, then we know we have a known
1586 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1587
1588 // To compute this, we first compute the potential carry bits. These are
1589 // the bits which may be modified. I'm not aware of a better way to do
1590 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001591 const APInt& RHSVal = RHS->getValue();
1592 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001593
1594 // Now that we know which bits have carries, compute the known-1/0 sets.
1595
1596 // Bits are known one if they are known zero in one operand and one in the
1597 // other, and there is no input carry.
1598 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1599 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1600
1601 // Bits are known zero if they are known zero in both operands and there
1602 // is no input carry.
1603 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1604 } else {
1605 // If the high-bits of this ADD are not demanded, then it does not demand
1606 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001607 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001608 // Right fill the mask of bits for this ADD to demand the most
1609 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001610 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001611 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1612 LHSKnownZero, LHSKnownOne, Depth+1))
1613 return true;
1614 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1615 LHSKnownZero, LHSKnownOne, Depth+1))
1616 return true;
1617 }
1618 }
1619 break;
1620 }
1621 case Instruction::Sub:
1622 // If the high-bits of this SUB are not demanded, then it does not demand
1623 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001624 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001625 // Right fill the mask of bits for this SUB to demand the most
1626 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001627 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001628 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001629 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1630 LHSKnownZero, LHSKnownOne, Depth+1))
1631 return true;
1632 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1633 LHSKnownZero, LHSKnownOne, Depth+1))
1634 return true;
1635 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001636 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1637 // the known zeros and ones.
1638 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001639 break;
1640 case Instruction::Shl:
1641 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001642 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001643 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1644 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001645 RHSKnownZero, RHSKnownOne, Depth+1))
1646 return true;
1647 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1648 "Bits known to be one AND zero?");
1649 RHSKnownZero <<= ShiftAmt;
1650 RHSKnownOne <<= ShiftAmt;
1651 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001652 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001653 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001654 }
1655 break;
1656 case Instruction::LShr:
1657 // For a logical shift right
1658 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001659 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001660
Reid Spencer8cb68342007-03-12 17:25:59 +00001661 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001662 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1663 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001664 RHSKnownZero, RHSKnownOne, Depth+1))
1665 return true;
1666 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1667 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001668 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1669 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001670 if (ShiftAmt) {
1671 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001672 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001673 RHSKnownZero |= HighBits; // high bits known zero.
1674 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001675 }
1676 break;
1677 case Instruction::AShr:
1678 // If this is an arithmetic shift right and only the low-bit is set, we can
1679 // always convert this into a logical shr, even if the shift amount is
1680 // variable. The low bit of the shift cannot be an input sign bit unless
1681 // the shift amount is >= the size of the datatype, which is undefined.
1682 if (DemandedMask == 1) {
1683 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001684 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001685 I->getOperand(0), I->getOperand(1), I->getName());
1686 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1687 return UpdateValueUsesWith(I, NewVal);
1688 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001689
1690 // If the sign bit is the only bit demanded by this ashr, then there is no
1691 // need to do it, the shift doesn't change the high bit.
1692 if (DemandedMask.isSignBit())
1693 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001694
1695 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001696 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001697
Reid Spencer8cb68342007-03-12 17:25:59 +00001698 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001699 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001700 // If any of the "high bits" are demanded, we should set the sign bit as
1701 // demanded.
1702 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1703 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001704 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001705 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001706 RHSKnownZero, RHSKnownOne, Depth+1))
1707 return true;
1708 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1709 "Bits known to be one AND zero?");
1710 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001711 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001712 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1713 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1714
1715 // Handle the sign bits.
1716 APInt SignBit(APInt::getSignBit(BitWidth));
1717 // Adjust to where it is now in the mask.
1718 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1719
1720 // If the input sign bit is known to be zero, or if none of the top bits
1721 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001722 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001723 (HighBits & ~DemandedMask) == HighBits) {
1724 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001725 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001726 I->getOperand(0), SA, I->getName());
1727 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1728 return UpdateValueUsesWith(I, NewVal);
1729 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1730 RHSKnownOne |= HighBits;
1731 }
1732 }
1733 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001734 case Instruction::SRem:
1735 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1736 APInt RA = Rem->getValue();
1737 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001738 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001739 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1740 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1741 LHSKnownZero, LHSKnownOne, Depth+1))
1742 return true;
1743
1744 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1745 LHSKnownZero |= ~LowBits;
1746 else if (LHSKnownOne[BitWidth-1])
1747 LHSKnownOne |= ~LowBits;
1748
1749 KnownZero |= LHSKnownZero & DemandedMask;
1750 KnownOne |= LHSKnownOne & DemandedMask;
1751
1752 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1753 }
1754 }
1755 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001756 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001757 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1758 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001759 if (RA.isPowerOf2()) {
1760 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001761 APInt Mask2 = LowBits & DemandedMask;
1762 KnownZero |= ~LowBits & DemandedMask;
1763 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1764 KnownZero, KnownOne, Depth+1))
1765 return true;
1766
1767 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001768 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001769 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001770 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001771
1772 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1773 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001774 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1775 KnownZero2, KnownOne2, Depth+1))
1776 return true;
1777
Dan Gohman23e8b712008-04-28 17:02:21 +00001778 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001779 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001780 KnownZero2, KnownOne2, Depth+1))
1781 return true;
1782
1783 Leaders = std::max(Leaders,
1784 KnownZero2.countLeadingOnes());
1785 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001786 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001787 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001788 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001789
1790 // If the client is only demanding bits that we know, return the known
1791 // constant.
1792 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1793 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1794 return false;
1795}
1796
Chris Lattner867b99f2006-10-05 06:55:50 +00001797
1798/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1799/// 64 or fewer elements. DemandedElts contains the set of elements that are
1800/// actually used by the caller. This method analyzes which elements of the
1801/// operand are undef and returns that information in UndefElts.
1802///
1803/// If the information about demanded elements can be used to simplify the
1804/// operation, the operation is simplified, then the resultant value is
1805/// returned. This returns null if no change was made.
1806Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1807 uint64_t &UndefElts,
1808 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001809 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001810 assert(VWidth <= 64 && "Vector too wide to analyze!");
1811 uint64_t EltMask = ~0ULL >> (64-VWidth);
1812 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1813 "Invalid DemandedElts!");
1814
1815 if (isa<UndefValue>(V)) {
1816 // If the entire vector is undefined, just return this info.
1817 UndefElts = EltMask;
1818 return 0;
1819 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1820 UndefElts = EltMask;
1821 return UndefValue::get(V->getType());
1822 }
1823
1824 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001825 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1826 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001827 Constant *Undef = UndefValue::get(EltTy);
1828
1829 std::vector<Constant*> Elts;
1830 for (unsigned i = 0; i != VWidth; ++i)
1831 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1832 Elts.push_back(Undef);
1833 UndefElts |= (1ULL << i);
1834 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1835 Elts.push_back(Undef);
1836 UndefElts |= (1ULL << i);
1837 } else { // Otherwise, defined.
1838 Elts.push_back(CP->getOperand(i));
1839 }
1840
1841 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001842 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001843 return NewCP != CP ? NewCP : 0;
1844 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001845 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001846 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001847 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001848 Constant *Zero = Constant::getNullValue(EltTy);
1849 Constant *Undef = UndefValue::get(EltTy);
1850 std::vector<Constant*> Elts;
1851 for (unsigned i = 0; i != VWidth; ++i)
1852 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1853 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001854 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001855 }
1856
1857 if (!V->hasOneUse()) { // Other users may use these bits.
1858 if (Depth != 0) { // Not at the root.
1859 // TODO: Just compute the UndefElts information recursively.
1860 return false;
1861 }
1862 return false;
1863 } else if (Depth == 10) { // Limit search depth.
1864 return false;
1865 }
1866
1867 Instruction *I = dyn_cast<Instruction>(V);
1868 if (!I) return false; // Only analyze instructions.
1869
1870 bool MadeChange = false;
1871 uint64_t UndefElts2;
1872 Value *TmpV;
1873 switch (I->getOpcode()) {
1874 default: break;
1875
1876 case Instruction::InsertElement: {
1877 // If this is a variable index, we don't know which element it overwrites.
1878 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001879 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001880 if (Idx == 0) {
1881 // Note that we can't propagate undef elt info, because we don't know
1882 // which elt is getting updated.
1883 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1884 UndefElts2, Depth+1);
1885 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1886 break;
1887 }
1888
1889 // If this is inserting an element that isn't demanded, remove this
1890 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001891 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001892 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1893 return AddSoonDeadInstToWorklist(*I, 0);
1894
1895 // Otherwise, the element inserted overwrites whatever was there, so the
1896 // input demanded set is simpler than the output set.
1897 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1898 DemandedElts & ~(1ULL << IdxNo),
1899 UndefElts, Depth+1);
1900 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1901
1902 // The inserted element is defined.
1903 UndefElts |= 1ULL << IdxNo;
1904 break;
1905 }
Chris Lattner69878332007-04-14 22:29:23 +00001906 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001907 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001908 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1909 if (!VTy) break;
1910 unsigned InVWidth = VTy->getNumElements();
1911 uint64_t InputDemandedElts = 0;
1912 unsigned Ratio;
1913
1914 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001915 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001916 // elements as are demanded of us.
1917 Ratio = 1;
1918 InputDemandedElts = DemandedElts;
1919 } else if (VWidth > InVWidth) {
1920 // Untested so far.
1921 break;
1922
1923 // If there are more elements in the result than there are in the source,
1924 // then an input element is live if any of the corresponding output
1925 // elements are live.
1926 Ratio = VWidth/InVWidth;
1927 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1928 if (DemandedElts & (1ULL << OutIdx))
1929 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1930 }
1931 } else {
1932 // Untested so far.
1933 break;
1934
1935 // If there are more elements in the source than there are in the result,
1936 // then an input element is live if the corresponding output element is
1937 // live.
1938 Ratio = InVWidth/VWidth;
1939 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1940 if (DemandedElts & (1ULL << InIdx/Ratio))
1941 InputDemandedElts |= 1ULL << InIdx;
1942 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001943
Chris Lattner69878332007-04-14 22:29:23 +00001944 // div/rem demand all inputs, because they don't want divide by zero.
1945 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1946 UndefElts2, Depth+1);
1947 if (TmpV) {
1948 I->setOperand(0, TmpV);
1949 MadeChange = true;
1950 }
1951
1952 UndefElts = UndefElts2;
1953 if (VWidth > InVWidth) {
1954 assert(0 && "Unimp");
1955 // If there are more elements in the result than there are in the source,
1956 // then an output element is undef if the corresponding input element is
1957 // undef.
1958 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1959 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1960 UndefElts |= 1ULL << OutIdx;
1961 } else if (VWidth < InVWidth) {
1962 assert(0 && "Unimp");
1963 // If there are more elements in the source than there are in the result,
1964 // then a result element is undef if all of the corresponding input
1965 // elements are undef.
1966 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1967 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1968 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1969 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1970 }
1971 break;
1972 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001973 case Instruction::And:
1974 case Instruction::Or:
1975 case Instruction::Xor:
1976 case Instruction::Add:
1977 case Instruction::Sub:
1978 case Instruction::Mul:
1979 // div/rem demand all inputs, because they don't want divide by zero.
1980 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1981 UndefElts, Depth+1);
1982 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1983 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1984 UndefElts2, Depth+1);
1985 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1986
1987 // Output elements are undefined if both are undefined. Consider things
1988 // like undef&0. The result is known zero, not undef.
1989 UndefElts &= UndefElts2;
1990 break;
1991
1992 case Instruction::Call: {
1993 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1994 if (!II) break;
1995 switch (II->getIntrinsicID()) {
1996 default: break;
1997
1998 // Binary vector operations that work column-wise. A dest element is a
1999 // function of the corresponding input elements from the two inputs.
2000 case Intrinsic::x86_sse_sub_ss:
2001 case Intrinsic::x86_sse_mul_ss:
2002 case Intrinsic::x86_sse_min_ss:
2003 case Intrinsic::x86_sse_max_ss:
2004 case Intrinsic::x86_sse2_sub_sd:
2005 case Intrinsic::x86_sse2_mul_sd:
2006 case Intrinsic::x86_sse2_min_sd:
2007 case Intrinsic::x86_sse2_max_sd:
2008 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2009 UndefElts, Depth+1);
2010 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2011 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2012 UndefElts2, Depth+1);
2013 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2014
2015 // If only the low elt is demanded and this is a scalarizable intrinsic,
2016 // scalarize it now.
2017 if (DemandedElts == 1) {
2018 switch (II->getIntrinsicID()) {
2019 default: break;
2020 case Intrinsic::x86_sse_sub_ss:
2021 case Intrinsic::x86_sse_mul_ss:
2022 case Intrinsic::x86_sse2_sub_sd:
2023 case Intrinsic::x86_sse2_mul_sd:
2024 // TODO: Lower MIN/MAX/ABS/etc
2025 Value *LHS = II->getOperand(1);
2026 Value *RHS = II->getOperand(2);
2027 // Extract the element as scalars.
2028 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2029 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2030
2031 switch (II->getIntrinsicID()) {
2032 default: assert(0 && "Case stmts out of sync!");
2033 case Intrinsic::x86_sse_sub_ss:
2034 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002035 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002036 II->getName()), *II);
2037 break;
2038 case Intrinsic::x86_sse_mul_ss:
2039 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002040 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002041 II->getName()), *II);
2042 break;
2043 }
2044
2045 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002046 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2047 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002048 InsertNewInstBefore(New, *II);
2049 AddSoonDeadInstToWorklist(*II, 0);
2050 return New;
2051 }
2052 }
2053
2054 // Output elements are undefined if both are undefined. Consider things
2055 // like undef&0. The result is known zero, not undef.
2056 UndefElts &= UndefElts2;
2057 break;
2058 }
2059 break;
2060 }
2061 }
2062 return MadeChange ? I : 0;
2063}
2064
Dan Gohman45b4e482008-05-19 22:14:15 +00002065/// ComputeNumSignBits - Return the number of times the sign bit of the
2066/// register is replicated into the other bits. We know that at least 1 bit
2067/// is always equal to the sign bit (itself), but other cases can give us
2068/// information. For example, immediately after an "ashr X, 2", we know that
2069/// the top 3 bits are all equal to each other, so we return 3.
2070///
2071unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2072 const IntegerType *Ty = cast<IntegerType>(V->getType());
2073 unsigned TyBits = Ty->getBitWidth();
2074 unsigned Tmp, Tmp2;
Dan Gohmana332f172008-05-23 02:28:01 +00002075 unsigned FirstAnswer = 1;
Dan Gohman45b4e482008-05-19 22:14:15 +00002076
2077 if (Depth == 6)
2078 return 1; // Limit search depth.
2079
2080 User *U = dyn_cast<User>(V);
2081 switch (getOpcode(V)) {
2082 default: break;
2083 case Instruction::SExt:
2084 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2085 return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2086
2087 case Instruction::AShr:
2088 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
Dan Gohmanf35c8822008-05-20 21:01:12 +00002089 // ashr X, C -> adds C sign bits.
Dan Gohman45b4e482008-05-19 22:14:15 +00002090 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2091 Tmp += C->getZExtValue();
2092 if (Tmp > TyBits) Tmp = TyBits;
2093 }
2094 return Tmp;
2095 case Instruction::Shl:
2096 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2097 // shl destroys sign bits.
2098 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2099 if (C->getZExtValue() >= TyBits || // Bad shift.
2100 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2101 return Tmp - C->getZExtValue();
2102 }
2103 break;
2104 case Instruction::And:
2105 case Instruction::Or:
Dan Gohmana332f172008-05-23 02:28:01 +00002106 case Instruction::Xor: // NOT is handled here.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002107 // Logical binary ops preserve the number of sign bits at the worst.
2108 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2109 if (Tmp != 1) {
2110 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohmana332f172008-05-23 02:28:01 +00002111 FirstAnswer = std::min(Tmp, Tmp2);
2112 // We computed what we know about the sign bits as our first
2113 // answer. Now proceed to the generic code that uses
2114 // ComputeMaskedBits, and pick whichever answer is better.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002115 }
Dan Gohmana332f172008-05-23 02:28:01 +00002116 break;
Dan Gohman45b4e482008-05-19 22:14:15 +00002117
2118 case Instruction::Select:
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002119 Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002120 if (Tmp == 1) return 1; // Early out.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002121 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002122 return std::min(Tmp, Tmp2);
2123
2124 case Instruction::Add:
2125 // Add can have at most one carry bit. Thus we know that the output
2126 // is, at worst, one more bit than the inputs.
2127 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2128 if (Tmp == 1) return 1; // Early out.
2129
2130 // Special case decrementing a value (ADD X, -1):
2131 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2132 if (CRHS->isAllOnesValue()) {
2133 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2134 APInt Mask = APInt::getAllOnesValue(TyBits);
2135 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2136
2137 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2138 // sign bits set.
2139 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2140 return TyBits;
2141
2142 // If we are subtracting one from a positive number, there is no carry
2143 // out of the result.
2144 if (KnownZero.isNegative())
2145 return Tmp;
2146 }
2147
2148 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2149 if (Tmp2 == 1) return 1;
2150 return std::min(Tmp, Tmp2)-1;
2151 break;
2152
2153 case Instruction::Sub:
2154 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2155 if (Tmp2 == 1) return 1;
2156
2157 // Handle NEG.
2158 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2159 if (CLHS->isNullValue()) {
2160 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2161 APInt Mask = APInt::getAllOnesValue(TyBits);
2162 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2163 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2164 // sign bits set.
2165 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2166 return TyBits;
2167
2168 // If the input is known to be positive (the sign bit is known clear),
2169 // the output of the NEG has the same number of sign bits as the input.
2170 if (KnownZero.isNegative())
2171 return Tmp2;
2172
2173 // Otherwise, we treat this like a SUB.
2174 }
2175
2176 // Sub can have at most one carry bit. Thus we know that the output
2177 // is, at worst, one more bit than the inputs.
2178 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2179 if (Tmp == 1) return 1; // Early out.
2180 return std::min(Tmp, Tmp2)-1;
2181 break;
2182 case Instruction::Trunc:
2183 // FIXME: it's tricky to do anything useful for this, but it is an important
2184 // case for targets like X86.
2185 break;
2186 }
2187
2188 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2189 // use this information.
2190 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2191 APInt Mask = APInt::getAllOnesValue(TyBits);
2192 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2193
2194 if (KnownZero.isNegative()) { // sign bit is 0
2195 Mask = KnownZero;
2196 } else if (KnownOne.isNegative()) { // sign bit is 1;
2197 Mask = KnownOne;
2198 } else {
2199 // Nothing known.
Dan Gohmana332f172008-05-23 02:28:01 +00002200 return FirstAnswer;
Dan Gohman45b4e482008-05-19 22:14:15 +00002201 }
2202
2203 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2204 // the number of identical bits in the top of the input value.
2205 Mask = ~Mask;
2206 Mask <<= Mask.getBitWidth()-TyBits;
2207 // Return # leading zeros. We use 'min' here in case Val was zero before
2208 // shifting. We don't want to return '64' as for an i32 "0".
Dan Gohmana332f172008-05-23 02:28:01 +00002209 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
Dan Gohman45b4e482008-05-19 22:14:15 +00002210}
2211
2212
Chris Lattner564a7272003-08-13 19:01:45 +00002213/// AssociativeOpt - Perform an optimization on an associative operator. This
2214/// function is designed to check a chain of associative operators for a
2215/// potential to apply a certain optimization. Since the optimization may be
2216/// applicable if the expression was reassociated, this checks the chain, then
2217/// reassociates the expression as necessary to expose the optimization
2218/// opportunity. This makes use of a special Functor, which must define
2219/// 'shouldApply' and 'apply' methods.
2220///
2221template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00002222static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00002223 unsigned Opcode = Root.getOpcode();
2224 Value *LHS = Root.getOperand(0);
2225
2226 // Quick check, see if the immediate LHS matches...
2227 if (F.shouldApply(LHS))
2228 return F.apply(Root);
2229
2230 // Otherwise, if the LHS is not of the same opcode as the root, return.
2231 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002232 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002233 // Should we apply this transform to the RHS?
2234 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2235
2236 // If not to the RHS, check to see if we should apply to the LHS...
2237 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2238 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2239 ShouldApply = true;
2240 }
2241
2242 // If the functor wants to apply the optimization to the RHS of LHSI,
2243 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2244 if (ShouldApply) {
2245 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002246
Chris Lattner564a7272003-08-13 19:01:45 +00002247 // Now all of the instructions are in the current basic block, go ahead
2248 // and perform the reassociation.
2249 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2250
2251 // First move the selected RHS to the LHS of the root...
2252 Root.setOperand(0, LHSI->getOperand(1));
2253
2254 // Make what used to be the LHS of the root be the user of the root...
2255 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002256 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002257 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2258 return 0;
2259 }
Chris Lattner65725312004-04-16 18:08:07 +00002260 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002261 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002262 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2263 BasicBlock::iterator ARI = &Root; ++ARI;
2264 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2265 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002266
2267 // Now propagate the ExtraOperand down the chain of instructions until we
2268 // get to LHSI.
2269 while (TmpLHSI != LHSI) {
2270 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002271 // Move the instruction to immediately before the chain we are
2272 // constructing to avoid breaking dominance properties.
2273 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2274 BB->getInstList().insert(ARI, NextLHSI);
2275 ARI = NextLHSI;
2276
Chris Lattner564a7272003-08-13 19:01:45 +00002277 Value *NextOp = NextLHSI->getOperand(1);
2278 NextLHSI->setOperand(1, ExtraOperand);
2279 TmpLHSI = NextLHSI;
2280 ExtraOperand = NextOp;
2281 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002282
Chris Lattner564a7272003-08-13 19:01:45 +00002283 // Now that the instructions are reassociated, have the functor perform
2284 // the transformation...
2285 return F.apply(Root);
2286 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002287
Chris Lattner564a7272003-08-13 19:01:45 +00002288 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2289 }
2290 return 0;
2291}
2292
Dan Gohman844731a2008-05-13 00:00:25 +00002293namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002294
Nick Lewycky02d639f2008-05-23 04:34:58 +00002295// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00002296struct AddRHS {
2297 Value *RHS;
2298 AddRHS(Value *rhs) : RHS(rhs) {}
2299 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2300 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00002301 return BinaryOperator::CreateShl(Add.getOperand(0),
2302 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002303 }
2304};
2305
2306// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2307// iff C1&C2 == 0
2308struct AddMaskingAnd {
2309 Constant *C2;
2310 AddMaskingAnd(Constant *c) : C2(c) {}
2311 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002312 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002313 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002314 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002315 }
2316 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002317 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002318 }
2319};
2320
Dan Gohman844731a2008-05-13 00:00:25 +00002321}
2322
Chris Lattner6e7ba452005-01-01 16:22:27 +00002323static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002324 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002325 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002326 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002327 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002328
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002329 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002330 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002331 }
2332
Chris Lattner2eefe512004-04-09 19:05:30 +00002333 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002334 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2335 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002336
Chris Lattner2eefe512004-04-09 19:05:30 +00002337 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2338 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002339 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2340 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002341 }
2342
2343 Value *Op0 = SO, *Op1 = ConstOperand;
2344 if (!ConstIsRHS)
2345 std::swap(Op0, Op1);
2346 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002347 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002348 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002349 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002350 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002351 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002352 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002353 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002354 abort();
2355 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002356 return IC->InsertNewInstBefore(New, I);
2357}
2358
2359// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2360// constant as the other operand, try to fold the binary operator into the
2361// select arguments. This also works for Cast instructions, which obviously do
2362// not have a second operand.
2363static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2364 InstCombiner *IC) {
2365 // Don't modify shared select instructions
2366 if (!SI->hasOneUse()) return 0;
2367 Value *TV = SI->getOperand(1);
2368 Value *FV = SI->getOperand(2);
2369
2370 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002371 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002372 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002373
Chris Lattner6e7ba452005-01-01 16:22:27 +00002374 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2375 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2376
Gabor Greif051a9502008-04-06 20:25:17 +00002377 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2378 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002379 }
2380 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002381}
2382
Chris Lattner4e998b22004-09-29 05:07:12 +00002383
2384/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2385/// node as operand #0, see if we can fold the instruction into the PHI (which
2386/// is only possible if all operands to the PHI are constants).
2387Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2388 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002389 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002390 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002391
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002392 // Check to see if all of the operands of the PHI are constants. If there is
2393 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002394 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002395 BasicBlock *NonConstBB = 0;
2396 for (unsigned i = 0; i != NumPHIValues; ++i)
2397 if (!isa<Constant>(PN->getIncomingValue(i))) {
2398 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002399 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002400 NonConstBB = PN->getIncomingBlock(i);
2401
2402 // If the incoming non-constant value is in I's block, we have an infinite
2403 // loop.
2404 if (NonConstBB == I.getParent())
2405 return 0;
2406 }
2407
2408 // If there is exactly one non-constant value, we can insert a copy of the
2409 // operation in that block. However, if this is a critical edge, we would be
2410 // inserting the computation one some other paths (e.g. inside a loop). Only
2411 // do this if the pred block is unconditionally branching into the phi block.
2412 if (NonConstBB) {
2413 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2414 if (!BI || !BI->isUnconditional()) return 0;
2415 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002416
2417 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002418 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002419 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002420 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002421 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002422
2423 // Next, add all of the operands to the PHI.
2424 if (I.getNumOperands() == 2) {
2425 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002426 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002427 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002428 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002429 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2430 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2431 else
2432 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002433 } else {
2434 assert(PN->getIncomingBlock(i) == NonConstBB);
2435 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002436 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002437 PN->getIncomingValue(i), C, "phitmp",
2438 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002439 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002440 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002441 CI->getPredicate(),
2442 PN->getIncomingValue(i), C, "phitmp",
2443 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002444 else
2445 assert(0 && "Unknown binop!");
2446
Chris Lattnerdbab3862007-03-02 21:28:56 +00002447 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002448 }
2449 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002450 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002451 } else {
2452 CastInst *CI = cast<CastInst>(&I);
2453 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002454 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002455 Value *InV;
2456 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002457 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002458 } else {
2459 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002460 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002461 I.getType(), "phitmp",
2462 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002463 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002464 }
2465 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002466 }
2467 }
2468 return ReplaceInstUsesWith(I, NewPN);
2469}
2470
Chris Lattner2454a2e2008-01-29 06:52:45 +00002471
2472/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2473/// value is never equal to -0.0.
2474///
2475/// Note that this function will need to be revisited when we support nondefault
2476/// rounding modes!
2477///
2478static bool CannotBeNegativeZero(const Value *V) {
2479 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2480 return !CFP->getValueAPF().isNegZero();
2481
Chris Lattner2454a2e2008-01-29 06:52:45 +00002482 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002483 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner2454a2e2008-01-29 06:52:45 +00002484 if (I->getOpcode() == Instruction::Add &&
2485 isa<ConstantFP>(I->getOperand(1)) &&
2486 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2487 return true;
2488
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002489 // sitofp and uitofp turn into +0.0 for zero.
2490 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2491 return true;
2492
Chris Lattner2454a2e2008-01-29 06:52:45 +00002493 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2494 if (II->getIntrinsicID() == Intrinsic::sqrt)
2495 return CannotBeNegativeZero(II->getOperand(1));
2496
2497 if (const CallInst *CI = dyn_cast<CallInst>(I))
2498 if (const Function *F = CI->getCalledFunction()) {
2499 if (F->isDeclaration()) {
2500 switch (F->getNameLen()) {
2501 case 3: // abs(x) != -0.0
2502 if (!strcmp(F->getNameStart(), "abs")) return true;
2503 break;
2504 case 4: // abs[lf](x) != -0.0
2505 if (!strcmp(F->getNameStart(), "absf")) return true;
2506 if (!strcmp(F->getNameStart(), "absl")) return true;
2507 break;
2508 }
2509 }
2510 }
2511 }
2512
2513 return false;
2514}
2515
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002516/// WillNotOverflowSignedAdd - Return true if we can prove that:
2517/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2518/// This basically requires proving that the add in the original type would not
2519/// overflow to change the sign bit or have a carry out.
2520bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2521 // There are different heuristics we can use for this. Here are some simple
2522 // ones.
2523
2524 // Add has the property that adding any two 2's complement numbers can only
2525 // have one carry bit which can change a sign. As such, if LHS and RHS each
2526 // have at least two sign bits, we know that the addition of the two values will
2527 // sign extend fine.
2528 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2529 return true;
2530
2531
2532 // If one of the operands only has one non-zero bit, and if the other operand
2533 // has a known-zero bit in a more significant place than it (not including the
2534 // sign bit) the ripple may go up to and fill the zero, but won't change the
2535 // sign. For example, (X & ~4) + 1.
2536
2537 // TODO: Implement.
2538
2539 return false;
2540}
2541
Chris Lattner2454a2e2008-01-29 06:52:45 +00002542
Chris Lattner7e708292002-06-25 16:13:24 +00002543Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002544 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002545 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002546
Chris Lattner66331a42004-04-10 22:01:55 +00002547 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002548 // X + undef -> undef
2549 if (isa<UndefValue>(RHS))
2550 return ReplaceInstUsesWith(I, RHS);
2551
Chris Lattner66331a42004-04-10 22:01:55 +00002552 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002553 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002554 if (RHSC->isNullValue())
2555 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002556 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002557 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2558 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002559 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002560 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002561
Chris Lattner66331a42004-04-10 22:01:55 +00002562 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002563 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002564 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002565 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002566 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002567 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002568
2569 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2570 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002571 if (!isa<VectorType>(I.getType())) {
2572 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2573 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2574 KnownZero, KnownOne))
2575 return &I;
2576 }
Chris Lattner66331a42004-04-10 22:01:55 +00002577 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002578
2579 if (isa<PHINode>(LHS))
2580 if (Instruction *NV = FoldOpIntoPhi(I))
2581 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002582
Chris Lattner4f637d42006-01-06 17:59:59 +00002583 ConstantInt *XorRHS = 0;
2584 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002585 if (isa<ConstantInt>(RHSC) &&
2586 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002587 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002588 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002589
Zhou Sheng4351c642007-04-02 08:20:41 +00002590 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002591 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2592 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002593 do {
2594 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002595 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2596 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002597 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2598 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002599 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002600 if (!MaskedValueIsZero(XorLHS,
2601 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002602 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002603 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002604 }
2605 }
2606 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002607 C0080Val = APIntOps::lshr(C0080Val, Size);
2608 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2609 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002610
Reid Spencer35c38852007-03-28 01:36:16 +00002611 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002612 // with funny bit widths then this switch statement should be removed. It
2613 // is just here to get the size of the "middle" type back up to something
2614 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002615 const Type *MiddleType = 0;
2616 switch (Size) {
2617 default: break;
2618 case 32: MiddleType = Type::Int32Ty; break;
2619 case 16: MiddleType = Type::Int16Ty; break;
2620 case 8: MiddleType = Type::Int8Ty; break;
2621 }
2622 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002623 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002624 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002625 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002626 }
2627 }
Chris Lattner66331a42004-04-10 22:01:55 +00002628 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002629
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002630 // X + X --> X << 1
Nick Lewycky02d639f2008-05-23 04:34:58 +00002631 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002632 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002633
2634 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2635 if (RHSI->getOpcode() == Instruction::Sub)
2636 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2637 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2638 }
2639 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2640 if (LHSI->getOpcode() == Instruction::Sub)
2641 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2642 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2643 }
Robert Bocchino71698282004-07-27 21:02:21 +00002644 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002645
Chris Lattner5c4afb92002-05-08 22:46:53 +00002646 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002647 // -A + -B --> -(A + B)
2648 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002649 if (LHS->getType()->isIntOrIntVector()) {
2650 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002651 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002652 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002653 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002654 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002655 }
2656
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002657 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002658 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002659
2660 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002661 if (!isa<Constant>(RHS))
2662 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002663 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002664
Misha Brukmanfd939082005-04-21 23:48:37 +00002665
Chris Lattner50af16a2004-11-13 19:50:12 +00002666 ConstantInt *C2;
2667 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2668 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002669 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002670
2671 // X*C1 + X*C2 --> X * (C1+C2)
2672 ConstantInt *C1;
2673 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002674 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002675 }
2676
2677 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002678 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002679 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002680
Chris Lattnere617c9e2007-01-05 02:17:46 +00002681 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002682 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2683 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002684
Chris Lattnerad3448c2003-02-18 19:57:07 +00002685
Chris Lattner564a7272003-08-13 19:01:45 +00002686 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002687 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002688 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2689 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002690
2691 // A+B --> A|B iff A and B have no bits set in common.
2692 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2693 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2694 APInt LHSKnownOne(IT->getBitWidth(), 0);
2695 APInt LHSKnownZero(IT->getBitWidth(), 0);
2696 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2697 if (LHSKnownZero != 0) {
2698 APInt RHSKnownOne(IT->getBitWidth(), 0);
2699 APInt RHSKnownZero(IT->getBitWidth(), 0);
2700 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2701
2702 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002703 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002704 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002705 }
2706 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002707
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002708 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002709 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002710 Value *W, *X, *Y, *Z;
2711 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2712 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2713 if (W != Y) {
2714 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002715 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002716 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002717 std::swap(W, X);
2718 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002719 std::swap(Y, Z);
2720 std::swap(W, X);
2721 }
2722 }
2723
2724 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002725 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002726 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002727 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002728 }
2729 }
2730 }
2731
Chris Lattner6b032052003-10-02 15:11:26 +00002732 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002733 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002734 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002735 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002736
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002737 // (X & FF00) + xx00 -> (X+xx00) & FF00
2738 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002739 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002740 if (Anded == CRHS) {
2741 // See if all bits from the first bit set in the Add RHS up are included
2742 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002743 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002744
2745 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002746 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002747
2748 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002749 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002750
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002751 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2752 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002753 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002754 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002755 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002756 }
2757 }
2758 }
2759
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002760 // Try to fold constant add into select arguments.
2761 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002762 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002763 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002764 }
2765
Reid Spencer1628cec2006-10-26 06:15:43 +00002766 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002767 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002768 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002769 CastInst *CI = dyn_cast<CastInst>(LHS);
2770 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002771 if (!CI) {
2772 CI = dyn_cast<CastInst>(RHS);
2773 Other = LHS;
2774 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002775 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002776 (CI->getType()->getPrimitiveSizeInBits() ==
2777 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002778 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002779 unsigned AS =
2780 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002781 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2782 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002783 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002784 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002785 }
2786 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002787
Chris Lattner42790482007-12-20 01:56:58 +00002788 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002789 {
2790 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2791 Value *Other = RHS;
2792 if (!SI) {
2793 SI = dyn_cast<SelectInst>(RHS);
2794 Other = LHS;
2795 }
Chris Lattner42790482007-12-20 01:56:58 +00002796 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002797 Value *TV = SI->getTrueValue();
2798 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002799 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002800
2801 // Can we fold the add into the argument of the select?
2802 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002803 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2804 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002805 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002806 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2807 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002808 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002809 }
2810 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002811
2812 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2813 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2814 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2815 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002816
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002817 // Check for (add (sext x), y), see if we can merge this into an
2818 // integer add followed by a sext.
2819 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2820 // (add (sext x), cst) --> (sext (add x, cst'))
2821 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2822 Constant *CI =
2823 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2824 if (LHSConv->hasOneUse() &&
2825 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2826 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2827 // Insert the new, smaller add.
2828 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2829 CI, "addconv");
2830 InsertNewInstBefore(NewAdd, I);
2831 return new SExtInst(NewAdd, I.getType());
2832 }
2833 }
2834
2835 // (add (sext x), (sext y)) --> (sext (add int x, y))
2836 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2837 // Only do this if x/y have the same type, if at last one of them has a
2838 // single use (so we don't increase the number of sexts), and if the
2839 // integer add will not overflow.
2840 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2841 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2842 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2843 RHSConv->getOperand(0))) {
2844 // Insert the new integer add.
2845 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2846 RHSConv->getOperand(0),
2847 "addconv");
2848 InsertNewInstBefore(NewAdd, I);
2849 return new SExtInst(NewAdd, I.getType());
2850 }
2851 }
2852 }
2853
2854 // Check for (add double (sitofp x), y), see if we can merge this into an
2855 // integer add followed by a promotion.
2856 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2857 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2858 // ... if the constant fits in the integer value. This is useful for things
2859 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2860 // requires a constant pool load, and generally allows the add to be better
2861 // instcombined.
2862 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2863 Constant *CI =
2864 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2865 if (LHSConv->hasOneUse() &&
2866 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2867 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2868 // Insert the new integer add.
2869 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2870 CI, "addconv");
2871 InsertNewInstBefore(NewAdd, I);
2872 return new SIToFPInst(NewAdd, I.getType());
2873 }
2874 }
2875
2876 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2877 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2878 // Only do this if x/y have the same type, if at last one of them has a
2879 // single use (so we don't increase the number of int->fp conversions),
2880 // and if the integer add will not overflow.
2881 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2882 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2883 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2884 RHSConv->getOperand(0))) {
2885 // Insert the new integer add.
2886 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2887 RHSConv->getOperand(0),
2888 "addconv");
2889 InsertNewInstBefore(NewAdd, I);
2890 return new SIToFPInst(NewAdd, I.getType());
2891 }
2892 }
2893 }
2894
Chris Lattner7e708292002-06-25 16:13:24 +00002895 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002896}
2897
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002898// isSignBit - Return true if the value represented by the constant only has the
2899// highest order bit set.
2900static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002901 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002902 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002903}
2904
Chris Lattner7e708292002-06-25 16:13:24 +00002905Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002907
Chris Lattner233f7dc2002-08-12 21:17:25 +00002908 if (Op0 == Op1) // sub X, X -> 0
2909 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002910
Chris Lattner233f7dc2002-08-12 21:17:25 +00002911 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002912 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002913 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002914
Chris Lattnere87597f2004-10-16 18:11:37 +00002915 if (isa<UndefValue>(Op0))
2916 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2917 if (isa<UndefValue>(Op1))
2918 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2919
Chris Lattnerd65460f2003-11-05 01:06:05 +00002920 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2921 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002922 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002923 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002924
Chris Lattnerd65460f2003-11-05 01:06:05 +00002925 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002926 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002927 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002928 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002929
Chris Lattner76b7a062007-01-15 07:02:54 +00002930 // -(X >>u 31) -> (X >>s 31)
2931 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002932 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002933 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002934 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002935 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002936 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002937 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002938 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002939 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002940 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002941 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002942 }
2943 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002944 }
2945 else if (SI->getOpcode() == Instruction::AShr) {
2946 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2947 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002948 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002949 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002950 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002951 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002952 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002953 }
2954 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002955 }
2956 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002957 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002958
2959 // Try to fold constant sub into select arguments.
2960 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002961 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002962 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002963
2964 if (isa<PHINode>(Op0))
2965 if (Instruction *NV = FoldOpIntoPhi(I))
2966 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002967 }
2968
Chris Lattner43d84d62005-04-07 16:15:25 +00002969 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2970 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002971 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002972 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002973 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002974 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002975 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002976 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2977 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2978 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002979 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002980 Op1I->getOperand(0));
2981 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002982 }
2983
Chris Lattnerfd059242003-10-15 16:48:29 +00002984 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002985 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2986 // is not used by anyone else...
2987 //
Chris Lattner0517e722004-02-02 20:09:56 +00002988 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002989 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002990 // Swap the two operands of the subexpr...
2991 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2992 Op1I->setOperand(0, IIOp1);
2993 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002994
Chris Lattnera2881962003-02-18 19:28:33 +00002995 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002996 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002997 }
2998
2999 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3000 //
3001 if (Op1I->getOpcode() == Instruction::And &&
3002 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3003 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3004
Chris Lattnerf523d062004-06-09 05:08:07 +00003005 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003006 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3007 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00003008 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00003009
Reid Spencerac5209e2006-10-16 23:08:08 +00003010 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00003011 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00003012 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00003013 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00003014 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003015 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00003016 ConstantExpr::getNeg(DivRHS));
3017
Chris Lattnerad3448c2003-02-18 19:57:07 +00003018 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00003019 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00003020 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003021 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003022 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00003023 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00003024
3025 // X - ((X / Y) * Y) --> X % Y
3026 if (Op1I->getOpcode() == Instruction::Mul)
3027 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3028 if (Op0 == I->getOperand(0) &&
3029 Op1I->getOperand(1) == I->getOperand(1)) {
3030 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003031 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003032 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003033 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003034 }
Chris Lattner40371712002-05-09 01:29:19 +00003035 }
Chris Lattner43d84d62005-04-07 16:15:25 +00003036 }
Chris Lattnera2881962003-02-18 19:28:33 +00003037
Chris Lattner9919e3d2006-12-02 00:13:08 +00003038 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003039 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00003040 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003041 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
3042 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3043 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
3044 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00003045 } else if (Op0I->getOpcode() == Instruction::Sub) {
3046 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003047 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003048 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003049 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003050
Chris Lattner50af16a2004-11-13 19:50:12 +00003051 ConstantInt *C1;
3052 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003053 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003054 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00003055
Chris Lattner50af16a2004-11-13 19:50:12 +00003056 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
3057 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003058 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00003059 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003060 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003061}
3062
Chris Lattnera0141b92007-07-15 20:42:37 +00003063/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3064/// comparison only checks the sign bit. If it only checks the sign bit, set
3065/// TrueIfSigned if the result of the comparison is true when the input value is
3066/// signed.
3067static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3068 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003069 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003070 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3071 TrueIfSigned = true;
3072 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003073 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3074 TrueIfSigned = true;
3075 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00003076 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3077 TrueIfSigned = false;
3078 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003079 case ICmpInst::ICMP_UGT:
3080 // True if LHS u> RHS and RHS == high-bit-mask - 1
3081 TrueIfSigned = true;
3082 return RHS->getValue() ==
3083 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3084 case ICmpInst::ICMP_UGE:
3085 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3086 TrueIfSigned = true;
3087 return RHS->getValue() ==
3088 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00003089 default:
3090 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00003091 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00003092}
3093
Chris Lattner7e708292002-06-25 16:13:24 +00003094Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003095 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00003096 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003097
Chris Lattnere87597f2004-10-16 18:11:37 +00003098 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
3099 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3100
Chris Lattner233f7dc2002-08-12 21:17:25 +00003101 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00003102 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3103 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00003104
3105 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00003106 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00003107 if (SI->getOpcode() == Instruction::Shl)
3108 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003109 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003110 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003111
Zhou Sheng843f07672007-04-19 05:39:12 +00003112 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00003113 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
3114 if (CI->equalsInt(1)) // X * 1 == X
3115 return ReplaceInstUsesWith(I, Op0);
3116 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003117 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003118
Zhou Sheng97b52c22007-03-29 01:57:21 +00003119 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003120 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003121 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00003122 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003123 }
Robert Bocchino71698282004-07-27 21:02:21 +00003124 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00003125 if (Op1F->isNullValue())
3126 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00003127
Chris Lattnera2881962003-02-18 19:28:33 +00003128 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3129 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00003130 // We need a better interface for long double here.
3131 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3132 if (Op1F->isExactlyValue(1.0))
3133 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00003134 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003135
3136 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3137 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00003138 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003139 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003140 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003141 Op1, "tmp");
3142 InsertNewInstBefore(Add, I);
3143 Value *C1C2 = ConstantExpr::getMul(Op1,
3144 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003145 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003146
3147 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003148
3149 // Try to fold constant mul into select arguments.
3150 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003151 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003152 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003153
3154 if (isa<PHINode>(Op0))
3155 if (Instruction *NV = FoldOpIntoPhi(I))
3156 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003157 }
3158
Chris Lattnera4f445b2003-03-10 23:23:04 +00003159 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3160 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003161 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003162
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003163 // If one of the operands of the multiply is a cast from a boolean value, then
3164 // we know the bool is either zero or one, so this is a 'masking' multiply.
3165 // See if we can simplify things based on how the boolean was originally
3166 // formed.
3167 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00003168 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003169 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003170 BoolCast = CI;
3171 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00003172 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003173 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003174 BoolCast = CI;
3175 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003176 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003177 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3178 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00003179 bool TIS = false;
3180
Reid Spencere4d87aa2006-12-23 06:05:41 +00003181 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00003182 // multiply into a shift/and combination.
3183 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00003184 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3185 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003186 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00003187 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00003188 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00003189 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00003190 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003191 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00003192 BoolCast->getOperand(0)->getName()+
3193 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003194
3195 // If the multiply type is not the same as the source type, sign extend
3196 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00003197 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00003198 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3199 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00003200 Instruction::CastOps opcode =
3201 (SrcBits == DstBits ? Instruction::BitCast :
3202 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3203 V = InsertCastBefore(opcode, V, I.getType(), I);
3204 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003205
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003206 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003207 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003208 }
3209 }
3210 }
3211
Chris Lattner7e708292002-06-25 16:13:24 +00003212 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003213}
3214
Reid Spencer1628cec2006-10-26 06:15:43 +00003215/// This function implements the transforms on div instructions that work
3216/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3217/// used by the visitors to those instructions.
3218/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003219Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003220 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003221
Chris Lattner50b2ca42008-02-19 06:12:18 +00003222 // undef / X -> 0 for integer.
3223 // undef / X -> undef for FP (the undef could be a snan).
3224 if (isa<UndefValue>(Op0)) {
3225 if (Op0->getType()->isFPOrFPVector())
3226 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003227 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003228 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003229
3230 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003231 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003232 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003233
Chris Lattner25feae52008-01-28 00:58:18 +00003234 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3235 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00003236 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00003237 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
3238 // the same basic block, then we replace the select with Y, and the
3239 // condition of the select with false (if the cond value is in the same BB).
3240 // If the select has uses other than the div, this allows them to be
3241 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3242 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003243 if (ST->isNullValue()) {
3244 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3245 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003246 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00003247 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3248 I.setOperand(1, SI->getOperand(2));
3249 else
3250 UpdateValueUsesWith(SI, SI->getOperand(2));
3251 return &I;
3252 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003253
Chris Lattner25feae52008-01-28 00:58:18 +00003254 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3255 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003256 if (ST->isNullValue()) {
3257 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3258 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003259 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00003260 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3261 I.setOperand(1, SI->getOperand(1));
3262 else
3263 UpdateValueUsesWith(SI, SI->getOperand(1));
3264 return &I;
3265 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003266 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003267
Reid Spencer1628cec2006-10-26 06:15:43 +00003268 return 0;
3269}
Misha Brukmanfd939082005-04-21 23:48:37 +00003270
Reid Spencer1628cec2006-10-26 06:15:43 +00003271/// This function implements the transforms common to both integer division
3272/// instructions (udiv and sdiv). It is called by the visitors to those integer
3273/// division instructions.
3274/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003275Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003276 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3277
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003278 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003279 if (Op0 == Op1) {
3280 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3281 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
3282 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3283 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3284 }
3285
3286 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
3287 return ReplaceInstUsesWith(I, CI);
3288 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003289
Reid Spencer1628cec2006-10-26 06:15:43 +00003290 if (Instruction *Common = commonDivTransforms(I))
3291 return Common;
3292
3293 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3294 // div X, 1 == X
3295 if (RHS->equalsInt(1))
3296 return ReplaceInstUsesWith(I, Op0);
3297
3298 // (X / C1) / C2 -> X / (C1*C2)
3299 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3300 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3301 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003302 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3303 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3304 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003305 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003306 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003307 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003308
Reid Spencerbca0e382007-03-23 20:05:17 +00003309 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003310 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3311 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3312 return R;
3313 if (isa<PHINode>(Op0))
3314 if (Instruction *NV = FoldOpIntoPhi(I))
3315 return NV;
3316 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003317 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003318
Chris Lattnera2881962003-02-18 19:28:33 +00003319 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003320 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003321 if (LHS->equalsInt(0))
3322 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3323
Reid Spencer1628cec2006-10-26 06:15:43 +00003324 return 0;
3325}
3326
3327Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3328 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3329
3330 // Handle the integer div common cases
3331 if (Instruction *Common = commonIDivTransforms(I))
3332 return Common;
3333
3334 // X udiv C^2 -> X >> C
3335 // Check to see if this is an unsigned division with an exact power of 2,
3336 // if so, convert to a right shift.
3337 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003338 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003339 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003340 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003341 }
3342
3343 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003344 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003345 if (RHSI->getOpcode() == Instruction::Shl &&
3346 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003347 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003348 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003349 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003350 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003351 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003352 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003353 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003354 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003355 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003356 }
3357 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003358 }
3359
Reid Spencer1628cec2006-10-26 06:15:43 +00003360 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3361 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003362 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003363 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003364 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003365 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003366 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003367 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003368 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003369 // Construct the "on true" case of the select
3370 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003371 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003372 Op0, TC, SI->getName()+".t");
3373 TSI = InsertNewInstBefore(TSI, I);
3374
3375 // Construct the "on false" case of the select
3376 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003377 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003378 Op0, FC, SI->getName()+".f");
3379 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003380
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003381 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003382 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003383 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003384 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003385 return 0;
3386}
3387
Reid Spencer1628cec2006-10-26 06:15:43 +00003388Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3389 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3390
3391 // Handle the integer div common cases
3392 if (Instruction *Common = commonIDivTransforms(I))
3393 return Common;
3394
3395 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3396 // sdiv X, -1 == -X
3397 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003398 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003399
3400 // -X/C -> X/-C
3401 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003402 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003403 }
3404
3405 // If the sign bits of both operands are zero (i.e. we can prove they are
3406 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003407 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003408 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003409 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003410 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003411 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003412 }
3413 }
3414
3415 return 0;
3416}
3417
3418Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3419 return commonDivTransforms(I);
3420}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003421
Reid Spencer0a783f72006-11-02 01:53:59 +00003422/// This function implements the transforms on rem instructions that work
3423/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3424/// is used by the visitors to those instructions.
3425/// @brief Transforms common to all three rem instructions
3426Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003427 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003428
Chris Lattner50b2ca42008-02-19 06:12:18 +00003429 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003430 if (Constant *LHS = dyn_cast<Constant>(Op0))
3431 if (LHS->isNullValue())
3432 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3433
Chris Lattner50b2ca42008-02-19 06:12:18 +00003434 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3435 if (I.getType()->isFPOrFPVector())
3436 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003437 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003438 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003439 if (isa<UndefValue>(Op1))
3440 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003441
3442 // Handle cases involving: rem X, (select Cond, Y, Z)
3443 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3444 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3445 // the same basic block, then we replace the select with Y, and the
3446 // condition of the select with false (if the cond value is in the same
3447 // BB). If the select has uses other than the div, this allows them to be
3448 // simplified also.
3449 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3450 if (ST->isNullValue()) {
3451 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3452 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003453 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003454 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3455 I.setOperand(1, SI->getOperand(2));
3456 else
3457 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003458 return &I;
3459 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003460 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3461 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3462 if (ST->isNullValue()) {
3463 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3464 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003465 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003466 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3467 I.setOperand(1, SI->getOperand(1));
3468 else
3469 UpdateValueUsesWith(SI, SI->getOperand(1));
3470 return &I;
3471 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003472 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003473
Reid Spencer0a783f72006-11-02 01:53:59 +00003474 return 0;
3475}
3476
3477/// This function implements the transforms common to both integer remainder
3478/// instructions (urem and srem). It is called by the visitors to those integer
3479/// remainder instructions.
3480/// @brief Common integer remainder transforms
3481Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3482 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3483
3484 if (Instruction *common = commonRemTransforms(I))
3485 return common;
3486
Chris Lattner857e8cd2004-12-12 21:48:58 +00003487 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003488 // X % 0 == undef, we don't need to preserve faults!
3489 if (RHS->equalsInt(0))
3490 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3491
Chris Lattnera2881962003-02-18 19:28:33 +00003492 if (RHS->equalsInt(1)) // X % 1 == 0
3493 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3494
Chris Lattner97943922006-02-28 05:49:21 +00003495 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3496 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3497 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3498 return R;
3499 } else if (isa<PHINode>(Op0I)) {
3500 if (Instruction *NV = FoldOpIntoPhi(I))
3501 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003502 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003503
3504 // See if we can fold away this rem instruction.
3505 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3506 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3507 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3508 KnownZero, KnownOne))
3509 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003510 }
Chris Lattnera2881962003-02-18 19:28:33 +00003511 }
3512
Reid Spencer0a783f72006-11-02 01:53:59 +00003513 return 0;
3514}
3515
3516Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3517 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3518
3519 if (Instruction *common = commonIRemTransforms(I))
3520 return common;
3521
3522 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3523 // X urem C^2 -> X and C
3524 // Check to see if this is an unsigned remainder with an exact power of 2,
3525 // if so, convert to a bitwise and.
3526 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003527 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003528 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003529 }
3530
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003531 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003532 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3533 if (RHSI->getOpcode() == Instruction::Shl &&
3534 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003535 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003536 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003537 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003538 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003539 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003540 }
3541 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003542 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003543
Reid Spencer0a783f72006-11-02 01:53:59 +00003544 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3545 // where C1&C2 are powers of two.
3546 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3547 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3548 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3549 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003550 if ((STO->getValue().isPowerOf2()) &&
3551 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003552 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003553 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003554 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003555 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003556 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003557 }
3558 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003559 }
3560
Chris Lattner3f5b8772002-05-06 16:14:14 +00003561 return 0;
3562}
3563
Reid Spencer0a783f72006-11-02 01:53:59 +00003564Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3565 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3566
Dan Gohmancff55092007-11-05 23:16:33 +00003567 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003568 if (Instruction *common = commonIRemTransforms(I))
3569 return common;
3570
3571 if (Value *RHSNeg = dyn_castNegVal(Op1))
3572 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003573 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003574 // X % -Y -> X % Y
3575 AddUsesToWorkList(I);
3576 I.setOperand(1, RHSNeg);
3577 return &I;
3578 }
3579
Dan Gohmancff55092007-11-05 23:16:33 +00003580 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003581 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003582 if (I.getType()->isInteger()) {
3583 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3584 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3585 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003586 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003587 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003588 }
3589
3590 return 0;
3591}
3592
3593Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003594 return commonRemTransforms(I);
3595}
3596
Chris Lattner8b170942002-08-09 23:47:40 +00003597// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003598static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003599 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003600 if (!isSigned)
3601 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3602 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003603}
3604
3605// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003606static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003607 if (!isSigned)
3608 return C->getValue() == 1; // unsigned
3609
3610 // Calculate 1111111111000000000000
3611 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3612 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003613}
3614
Chris Lattner457dd822004-06-09 07:59:58 +00003615// isOneBitSet - Return true if there is exactly one bit set in the specified
3616// constant.
3617static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003618 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003619}
3620
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003621// isHighOnes - Return true if the constant is of the form 1+0+.
3622// This is the same as lowones(~X).
3623static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003624 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003625}
3626
Reid Spencere4d87aa2006-12-23 06:05:41 +00003627/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003628/// are carefully arranged to allow folding of expressions such as:
3629///
3630/// (A < B) | (A > B) --> (A != B)
3631///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003632/// Note that this is only valid if the first and second predicates have the
3633/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003634///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003635/// Three bits are used to represent the condition, as follows:
3636/// 0 A > B
3637/// 1 A == B
3638/// 2 A < B
3639///
3640/// <=> Value Definition
3641/// 000 0 Always false
3642/// 001 1 A > B
3643/// 010 2 A == B
3644/// 011 3 A >= B
3645/// 100 4 A < B
3646/// 101 5 A != B
3647/// 110 6 A <= B
3648/// 111 7 Always true
3649///
3650static unsigned getICmpCode(const ICmpInst *ICI) {
3651 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003652 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653 case ICmpInst::ICMP_UGT: return 1; // 001
3654 case ICmpInst::ICMP_SGT: return 1; // 001
3655 case ICmpInst::ICMP_EQ: return 2; // 010
3656 case ICmpInst::ICMP_UGE: return 3; // 011
3657 case ICmpInst::ICMP_SGE: return 3; // 011
3658 case ICmpInst::ICMP_ULT: return 4; // 100
3659 case ICmpInst::ICMP_SLT: return 4; // 100
3660 case ICmpInst::ICMP_NE: return 5; // 101
3661 case ICmpInst::ICMP_ULE: return 6; // 110
3662 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003663 // True -> 7
3664 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003665 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003666 return 0;
3667 }
3668}
3669
Reid Spencere4d87aa2006-12-23 06:05:41 +00003670/// getICmpValue - This is the complement of getICmpCode, which turns an
3671/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003672/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003673/// of predicate to use in new icmp instructions.
3674static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3675 switch (code) {
3676 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003677 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003678 case 1:
3679 if (sign)
3680 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3681 else
3682 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3683 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3684 case 3:
3685 if (sign)
3686 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3687 else
3688 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3689 case 4:
3690 if (sign)
3691 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3692 else
3693 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3694 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3695 case 6:
3696 if (sign)
3697 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3698 else
3699 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003700 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003701 }
3702}
3703
Reid Spencere4d87aa2006-12-23 06:05:41 +00003704static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3705 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3706 (ICmpInst::isSignedPredicate(p1) &&
3707 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3708 (ICmpInst::isSignedPredicate(p2) &&
3709 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3710}
3711
3712namespace {
3713// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3714struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003715 InstCombiner &IC;
3716 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003717 ICmpInst::Predicate pred;
3718 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3719 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3720 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003721 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003722 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3723 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003724 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3725 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003726 return false;
3727 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003728 Instruction *apply(Instruction &Log) const {
3729 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3730 if (ICI->getOperand(0) != LHS) {
3731 assert(ICI->getOperand(1) == LHS);
3732 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003733 }
3734
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003735 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003736 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003737 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003738 unsigned Code;
3739 switch (Log.getOpcode()) {
3740 case Instruction::And: Code = LHSCode & RHSCode; break;
3741 case Instruction::Or: Code = LHSCode | RHSCode; break;
3742 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003743 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003744 }
3745
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003746 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3747 ICmpInst::isSignedPredicate(ICI->getPredicate());
3748
3749 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003750 if (Instruction *I = dyn_cast<Instruction>(RV))
3751 return I;
3752 // Otherwise, it's a constant boolean value...
3753 return IC.ReplaceInstUsesWith(Log, RV);
3754 }
3755};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003756} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003757
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003758// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3759// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003760// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003761Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003762 ConstantInt *OpRHS,
3763 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003764 BinaryOperator &TheAnd) {
3765 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003766 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003767 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003768 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003769
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003770 switch (Op->getOpcode()) {
3771 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003772 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003773 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003774 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003775 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003776 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003777 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003778 }
3779 break;
3780 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003781 if (Together == AndRHS) // (X | C) & C --> C
3782 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003783
Chris Lattner6e7ba452005-01-01 16:22:27 +00003784 if (Op->hasOneUse() && Together != OpRHS) {
3785 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003786 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003787 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003788 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003789 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003790 }
3791 break;
3792 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003793 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003794 // Adding a one to a single bit bit-field should be turned into an XOR
3795 // of the bit. First thing to check is to see if this AND is with a
3796 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003797 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003798
3799 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003800 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003801 // Ok, at this point, we know that we are masking the result of the
3802 // ADD down to exactly one bit. If the constant we are adding has
3803 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003804 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003805
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003806 // Check to see if any bits below the one bit set in AndRHSV are set.
3807 if ((AddRHS & (AndRHSV-1)) == 0) {
3808 // If not, the only thing that can effect the output of the AND is
3809 // the bit specified by AndRHSV. If that bit is set, the effect of
3810 // the XOR is to toggle the bit. If it is clear, then the ADD has
3811 // no effect.
3812 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3813 TheAnd.setOperand(0, X);
3814 return &TheAnd;
3815 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003816 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003817 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003818 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003819 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003820 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003821 }
3822 }
3823 }
3824 }
3825 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003826
3827 case Instruction::Shl: {
3828 // We know that the AND will not produce any of the bits shifted in, so if
3829 // the anded constant includes them, clear them now!
3830 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003831 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003832 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003833 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3834 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003835
Zhou Sheng290bec52007-03-29 08:15:12 +00003836 if (CI->getValue() == ShlMask) {
3837 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003838 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3839 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003840 TheAnd.setOperand(1, CI);
3841 return &TheAnd;
3842 }
3843 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003844 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003845 case Instruction::LShr:
3846 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003847 // We know that the AND will not produce any of the bits shifted in, so if
3848 // the anded constant includes them, clear them now! This only applies to
3849 // unsigned shifts, because a signed shr may bring in set bits!
3850 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003851 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003852 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003853 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3854 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003855
Zhou Sheng290bec52007-03-29 08:15:12 +00003856 if (CI->getValue() == ShrMask) {
3857 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003858 return ReplaceInstUsesWith(TheAnd, Op);
3859 } else if (CI != AndRHS) {
3860 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3861 return &TheAnd;
3862 }
3863 break;
3864 }
3865 case Instruction::AShr:
3866 // Signed shr.
3867 // See if this is shifting in some sign extension, then masking it out
3868 // with an and.
3869 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003870 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003871 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003872 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3873 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003874 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003875 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003876 // Make the argument unsigned.
3877 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003878 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003879 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003880 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003881 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003882 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003883 }
3884 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003885 }
3886 return 0;
3887}
3888
Chris Lattner8b170942002-08-09 23:47:40 +00003889
Chris Lattnera96879a2004-09-29 17:40:11 +00003890/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3891/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003892/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3893/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003894/// insert new instructions.
3895Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003896 bool isSigned, bool Inside,
3897 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003898 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003899 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003900 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003901
Chris Lattnera96879a2004-09-29 17:40:11 +00003902 if (Inside) {
3903 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003904 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003905
Reid Spencere4d87aa2006-12-23 06:05:41 +00003906 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003907 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003908 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003909 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3910 return new ICmpInst(pred, V, Hi);
3911 }
3912
3913 // Emit V-Lo <u Hi-Lo
3914 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003915 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003916 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003917 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3918 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003919 }
3920
3921 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003922 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003923
Reid Spencere4e40032007-03-21 23:19:50 +00003924 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003925 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003926 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003927 ICmpInst::Predicate pred = (isSigned ?
3928 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3929 return new ICmpInst(pred, V, Hi);
3930 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003931
Reid Spencere4e40032007-03-21 23:19:50 +00003932 // Emit V-Lo >u Hi-1-Lo
3933 // Note that Hi has already had one subtracted from it, above.
3934 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003935 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003936 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003937 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3938 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003939}
3940
Chris Lattner7203e152005-09-18 07:22:02 +00003941// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3942// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3943// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3944// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003945static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003946 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003947 uint32_t BitWidth = Val->getType()->getBitWidth();
3948 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003949
3950 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003951 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003952 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003953 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003954 return true;
3955}
3956
Chris Lattner7203e152005-09-18 07:22:02 +00003957/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3958/// where isSub determines whether the operator is a sub. If we can fold one of
3959/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003960///
3961/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3962/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3963/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3964///
3965/// return (A +/- B).
3966///
3967Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003968 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003969 Instruction &I) {
3970 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3971 if (!LHSI || LHSI->getNumOperands() != 2 ||
3972 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3973
3974 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3975
3976 switch (LHSI->getOpcode()) {
3977 default: return 0;
3978 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003979 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003980 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003981 if ((Mask->getValue().countLeadingZeros() +
3982 Mask->getValue().countPopulation()) ==
3983 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003984 break;
3985
3986 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3987 // part, we don't need any explicit masks to take them out of A. If that
3988 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003989 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003990 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003991 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003992 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003993 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003994 break;
3995 }
3996 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003997 return 0;
3998 case Instruction::Or:
3999 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004000 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004001 if ((Mask->getValue().countLeadingZeros() +
4002 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00004003 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004004 break;
4005 return 0;
4006 }
4007
4008 Instruction *New;
4009 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004010 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004011 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004012 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004013 return InsertNewInstBefore(New, I);
4014}
4015
Chris Lattner7e708292002-06-25 16:13:24 +00004016Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004017 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004018 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004019
Chris Lattnere87597f2004-10-16 18:11:37 +00004020 if (isa<UndefValue>(Op1)) // X & undef -> 0
4021 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4022
Chris Lattner6e7ba452005-01-01 16:22:27 +00004023 // and X, X = X
4024 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004025 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004026
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004027 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004028 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00004029 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00004030 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4031 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4032 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00004033 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00004034 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00004035 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004036 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004037 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004038 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004039 } else if (isa<ConstantAggregateZero>(Op1)) {
4040 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004041 }
4042 }
Chris Lattner9ca96412006-02-08 03:25:32 +00004043
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004044 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004045 const APInt& AndRHSMask = AndRHS->getValue();
4046 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004047
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004048 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004049 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004050 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004051 Value *Op0LHS = Op0I->getOperand(0);
4052 Value *Op0RHS = Op0I->getOperand(1);
4053 switch (Op0I->getOpcode()) {
4054 case Instruction::Xor:
4055 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004056 // If the mask is only needed on one incoming arm, push it up.
4057 if (Op0I->hasOneUse()) {
4058 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4059 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004060 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004061 Op0RHS->getName()+".masked");
4062 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004063 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004064 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004065 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004066 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004067 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4068 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004069 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004070 Op0LHS->getName()+".masked");
4071 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004072 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004073 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4074 }
4075 }
4076
Chris Lattner6e7ba452005-01-01 16:22:27 +00004077 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004078 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004079 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4080 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4081 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4082 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004083 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004084 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004085 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004086 break;
4087
4088 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004089 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4090 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4091 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4092 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004093 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00004094 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004095 }
4096
Chris Lattner58403262003-07-23 19:25:52 +00004097 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004098 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004099 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004100 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004101 // If this is an integer truncation or change from signed-to-unsigned, and
4102 // if the source is an and/or with immediate, transform it. This
4103 // frequently occurs for bitfield accesses.
4104 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004105 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004106 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004107 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004108 if (CastOp->getOpcode() == Instruction::And) {
4109 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004110 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4111 // This will fold the two constants together, which may allow
4112 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004113 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004114 CastOp->getOperand(0), I.getType(),
4115 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004116 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004117 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00004118 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00004119 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004120 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004121 } else if (CastOp->getOpcode() == Instruction::Or) {
4122 // Change: and (cast (or X, C1) to T), C2
4123 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00004124 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00004125 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4126 return ReplaceInstUsesWith(I, AndRHS);
4127 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004128 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004129 }
Chris Lattner06782f82003-07-23 19:36:21 +00004130 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004131
4132 // Try to fold constant and into select arguments.
4133 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004134 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004135 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004136 if (isa<PHINode>(Op0))
4137 if (Instruction *NV = FoldOpIntoPhi(I))
4138 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004139 }
4140
Chris Lattner8d969642003-03-10 23:06:50 +00004141 Value *Op0NotVal = dyn_castNotVal(Op0);
4142 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004143
Chris Lattner5b62aa72004-06-18 06:07:51 +00004144 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4145 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4146
Misha Brukmancb6267b2004-07-30 12:50:08 +00004147 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004148 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004149 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004150 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004151 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004152 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004153 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004154
4155 {
Chris Lattner003b6202007-06-15 05:58:24 +00004156 Value *A = 0, *B = 0, *C = 0, *D = 0;
4157 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004158 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4159 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004160
4161 // (A|B) & ~(A&B) -> A^B
4162 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4163 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004164 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004165 }
4166 }
4167
4168 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004169 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4170 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004171
4172 // ~(A&B) & (A|B) -> A^B
4173 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4174 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004175 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004176 }
4177 }
Chris Lattner64daab52006-04-01 08:03:55 +00004178
4179 if (Op0->hasOneUse() &&
4180 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4181 if (A == Op1) { // (A^B)&A -> A&(A^B)
4182 I.swapOperands(); // Simplify below
4183 std::swap(Op0, Op1);
4184 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4185 cast<BinaryOperator>(Op0)->swapOperands();
4186 I.swapOperands(); // Simplify below
4187 std::swap(Op0, Op1);
4188 }
4189 }
4190 if (Op1->hasOneUse() &&
4191 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4192 if (B == Op0) { // B&(A^B) -> B&(B^A)
4193 cast<BinaryOperator>(Op1)->swapOperands();
4194 std::swap(A, B);
4195 }
4196 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004197 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004198 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004199 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004200 }
4201 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004202 }
4203
Reid Spencere4d87aa2006-12-23 06:05:41 +00004204 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4205 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4206 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004207 return R;
4208
Chris Lattner955f3312004-09-28 21:48:02 +00004209 Value *LHSVal, *RHSVal;
4210 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004211 ICmpInst::Predicate LHSCC, RHSCC;
4212 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4213 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4214 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4215 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4216 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4217 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4218 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00004219 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4220
4221 // Don't try to fold ICMP_SLT + ICMP_ULT.
4222 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4223 ICmpInst::isSignedPredicate(LHSCC) ==
4224 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00004225 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00004226 ICmpInst::Predicate GT;
4227 if (ICmpInst::isSignedPredicate(LHSCC) ||
4228 (ICmpInst::isEquality(LHSCC) &&
4229 ICmpInst::isSignedPredicate(RHSCC)))
4230 GT = ICmpInst::ICMP_SGT;
4231 else
4232 GT = ICmpInst::ICMP_UGT;
4233
Reid Spencere4d87aa2006-12-23 06:05:41 +00004234 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4235 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00004236 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00004237 std::swap(LHS, RHS);
4238 std::swap(LHSCst, RHSCst);
4239 std::swap(LHSCC, RHSCC);
4240 }
4241
Reid Spencere4d87aa2006-12-23 06:05:41 +00004242 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00004243 // comparing a value against two constants and and'ing the result
4244 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004245 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4246 // (from the FoldICmpLogical check above), that the two constants
4247 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00004248 assert(LHSCst != RHSCst && "Compares not folded above?");
4249
4250 switch (LHSCC) {
4251 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004252 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00004253 switch (RHSCC) {
4254 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004255 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4256 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4257 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004258 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004259 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4260 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4261 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00004262 return ReplaceInstUsesWith(I, LHS);
4263 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004264 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00004265 switch (RHSCC) {
4266 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004267 case ICmpInst::ICMP_ULT:
4268 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4269 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4270 break; // (X != 13 & X u< 15) -> no change
4271 case ICmpInst::ICMP_SLT:
4272 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4273 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4274 break; // (X != 13 & X s< 15) -> no change
4275 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4276 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4277 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004278 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004279 case ICmpInst::ICMP_NE:
4280 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004281 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004282 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004283 LHSVal->getName()+".off");
4284 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004285 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4286 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004287 }
4288 break; // (X != 13 & X != 15) -> no change
4289 }
4290 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004291 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004292 switch (RHSCC) {
4293 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004294 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4295 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004296 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004297 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4298 break;
4299 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4300 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004301 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004302 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4303 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004304 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004305 break;
4306 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004307 switch (RHSCC) {
4308 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004309 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4310 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004311 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004312 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4313 break;
4314 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4315 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004316 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004317 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4318 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004319 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004320 break;
4321 case ICmpInst::ICMP_UGT:
4322 switch (RHSCC) {
4323 default: assert(0 && "Unknown integer condition code!");
4324 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4325 return ReplaceInstUsesWith(I, LHS);
4326 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4327 return ReplaceInstUsesWith(I, RHS);
4328 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4329 break;
4330 case ICmpInst::ICMP_NE:
4331 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4332 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4333 break; // (X u> 13 & X != 15) -> no change
4334 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4335 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4336 true, I);
4337 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4338 break;
4339 }
4340 break;
4341 case ICmpInst::ICMP_SGT:
4342 switch (RHSCC) {
4343 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004344 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004345 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4346 return ReplaceInstUsesWith(I, RHS);
4347 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4348 break;
4349 case ICmpInst::ICMP_NE:
4350 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4351 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4352 break; // (X s> 13 & X != 15) -> no change
4353 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4354 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4355 true, I);
4356 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4357 break;
4358 }
4359 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004360 }
4361 }
4362 }
4363
Chris Lattner6fc205f2006-05-05 06:39:07 +00004364 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004365 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4366 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4367 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4368 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004369 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004370 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004371 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4372 I.getType(), TD) &&
4373 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4374 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004375 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004376 Op1C->getOperand(0),
4377 I.getName());
4378 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004379 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004380 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004381 }
Chris Lattnere511b742006-11-14 07:46:50 +00004382
4383 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004384 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4385 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4386 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004387 SI0->getOperand(1) == SI1->getOperand(1) &&
4388 (SI0->hasOneUse() || SI1->hasOneUse())) {
4389 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004390 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004391 SI1->getOperand(0),
4392 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004393 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004394 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004395 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004396 }
4397
Chris Lattner99c65742007-10-24 05:38:08 +00004398 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4399 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4400 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4401 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4402 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4403 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4404 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4405 // If either of the constants are nans, then the whole thing returns
4406 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004407 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004408 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4409 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4410 RHS->getOperand(0));
4411 }
4412 }
4413 }
4414
Chris Lattner7e708292002-06-25 16:13:24 +00004415 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004416}
4417
Chris Lattnerafe91a52006-06-15 19:07:26 +00004418/// CollectBSwapParts - Look to see if the specified value defines a single byte
4419/// in the result. If it does, and if the specified byte hasn't been filled in
4420/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004421static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004422 Instruction *I = dyn_cast<Instruction>(V);
4423 if (I == 0) return true;
4424
4425 // If this is an or instruction, it is an inner node of the bswap.
4426 if (I->getOpcode() == Instruction::Or)
4427 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4428 CollectBSwapParts(I->getOperand(1), ByteValues);
4429
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004430 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004431 // If this is a shift by a constant int, and it is "24", then its operand
4432 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004433 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004434 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004435 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004436 8*(ByteValues.size()-1))
4437 return true;
4438
4439 unsigned DestNo;
4440 if (I->getOpcode() == Instruction::Shl) {
4441 // X << 24 defines the top byte with the lowest of the input bytes.
4442 DestNo = ByteValues.size()-1;
4443 } else {
4444 // X >>u 24 defines the low byte with the highest of the input bytes.
4445 DestNo = 0;
4446 }
4447
4448 // If the destination byte value is already defined, the values are or'd
4449 // together, which isn't a bswap (unless it's an or of the same bits).
4450 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4451 return true;
4452 ByteValues[DestNo] = I->getOperand(0);
4453 return false;
4454 }
4455
4456 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4457 // don't have this.
4458 Value *Shift = 0, *ShiftLHS = 0;
4459 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4460 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4461 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4462 return true;
4463 Instruction *SI = cast<Instruction>(Shift);
4464
4465 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004466 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4467 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004468 return true;
4469
4470 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4471 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004472 if (AndAmt->getValue().getActiveBits() > 64)
4473 return true;
4474 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004475 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004476 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004477 break;
4478 // Unknown mask for bswap.
4479 if (DestByte == ByteValues.size()) return true;
4480
Reid Spencerb83eb642006-10-20 07:07:24 +00004481 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004482 unsigned SrcByte;
4483 if (SI->getOpcode() == Instruction::Shl)
4484 SrcByte = DestByte - ShiftBytes;
4485 else
4486 SrcByte = DestByte + ShiftBytes;
4487
4488 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4489 if (SrcByte != ByteValues.size()-DestByte-1)
4490 return true;
4491
4492 // If the destination byte value is already defined, the values are or'd
4493 // together, which isn't a bswap (unless it's an or of the same bits).
4494 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4495 return true;
4496 ByteValues[DestByte] = SI->getOperand(0);
4497 return false;
4498}
4499
4500/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4501/// If so, insert the new bswap intrinsic and return it.
4502Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004503 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4504 if (!ITy || ITy->getBitWidth() % 16)
4505 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004506
4507 /// ByteValues - For each byte of the result, we keep track of which value
4508 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004509 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004510 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004511
4512 // Try to find all the pieces corresponding to the bswap.
4513 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4514 CollectBSwapParts(I.getOperand(1), ByteValues))
4515 return 0;
4516
4517 // Check to see if all of the bytes come from the same value.
4518 Value *V = ByteValues[0];
4519 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4520
4521 // Check to make sure that all of the bytes come from the same value.
4522 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4523 if (ByteValues[i] != V)
4524 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004525 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004526 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004527 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004528 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004529}
4530
4531
Chris Lattner7e708292002-06-25 16:13:24 +00004532Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004533 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004534 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004535
Chris Lattner42593e62007-03-24 23:56:43 +00004536 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004537 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004538
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004539 // or X, X = X
4540 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004541 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004542
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004543 // See if we can simplify any instructions used by the instruction whose sole
4544 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004545 if (!isa<VectorType>(I.getType())) {
4546 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4547 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4548 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4549 KnownZero, KnownOne))
4550 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004551 } else if (isa<ConstantAggregateZero>(Op1)) {
4552 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4553 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4554 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4555 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004556 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004557
4558
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004559
Chris Lattner3f5b8772002-05-06 16:14:14 +00004560 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004561 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004562 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004563 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4564 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004565 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004566 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004567 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004568 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004569 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004570 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004571
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004572 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4573 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004574 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004575 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004576 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004577 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004578 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004579 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004580
4581 // Try to fold constant and into select arguments.
4582 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004583 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004584 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004585 if (isa<PHINode>(Op0))
4586 if (Instruction *NV = FoldOpIntoPhi(I))
4587 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004588 }
4589
Chris Lattner4f637d42006-01-06 17:59:59 +00004590 Value *A = 0, *B = 0;
4591 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004592
4593 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4594 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4595 return ReplaceInstUsesWith(I, Op1);
4596 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4597 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4598 return ReplaceInstUsesWith(I, Op0);
4599
Chris Lattner6423d4c2006-07-10 20:25:24 +00004600 // (A | B) | C and A | (B | C) -> bswap if possible.
4601 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004602 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004603 match(Op1, m_Or(m_Value(), m_Value())) ||
4604 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4605 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004606 if (Instruction *BSwap = MatchBSwap(I))
4607 return BSwap;
4608 }
4609
Chris Lattner6e4c6492005-05-09 04:58:36 +00004610 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4611 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004612 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004613 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004614 InsertNewInstBefore(NOr, I);
4615 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004616 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004617 }
4618
4619 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4620 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004621 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004622 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004623 InsertNewInstBefore(NOr, I);
4624 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004625 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004626 }
4627
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004628 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004629 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004630 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4631 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004632 Value *V1 = 0, *V2 = 0, *V3 = 0;
4633 C1 = dyn_cast<ConstantInt>(C);
4634 C2 = dyn_cast<ConstantInt>(D);
4635 if (C1 && C2) { // (A & C1)|(B & C2)
4636 // If we have: ((V + N) & C1) | (V & C2)
4637 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4638 // replace with V+N.
4639 if (C1->getValue() == ~C2->getValue()) {
4640 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4641 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4642 // Add commutes, try both ways.
4643 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4644 return ReplaceInstUsesWith(I, A);
4645 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4646 return ReplaceInstUsesWith(I, A);
4647 }
4648 // Or commutes, try both ways.
4649 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4650 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4651 // Add commutes, try both ways.
4652 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4653 return ReplaceInstUsesWith(I, B);
4654 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4655 return ReplaceInstUsesWith(I, B);
4656 }
4657 }
Chris Lattner044e5332007-04-08 08:01:49 +00004658 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004659 }
4660
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004661 // Check to see if we have any common things being and'ed. If so, find the
4662 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004663 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4664 if (A == B) // (A & C)|(A & D) == A & (C|D)
4665 V1 = A, V2 = C, V3 = D;
4666 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4667 V1 = A, V2 = B, V3 = C;
4668 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4669 V1 = C, V2 = A, V3 = D;
4670 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4671 V1 = C, V2 = A, V3 = B;
4672
4673 if (V1) {
4674 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004675 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4676 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004677 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004678 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004679 }
Chris Lattnere511b742006-11-14 07:46:50 +00004680
4681 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004682 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4683 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4684 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004685 SI0->getOperand(1) == SI1->getOperand(1) &&
4686 (SI0->hasOneUse() || SI1->hasOneUse())) {
4687 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004688 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004689 SI1->getOperand(0),
4690 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004691 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004692 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004693 }
4694 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004695
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004696 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4697 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004698 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004699 } else {
4700 A = 0;
4701 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004702 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004703 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4704 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004705 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004706
Misha Brukmancb6267b2004-07-30 12:50:08 +00004707 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004708 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004709 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004710 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004711 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004712 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004713 }
Chris Lattnera2881962003-02-18 19:28:33 +00004714
Reid Spencere4d87aa2006-12-23 06:05:41 +00004715 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4716 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4717 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004718 return R;
4719
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004720 Value *LHSVal, *RHSVal;
4721 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004722 ICmpInst::Predicate LHSCC, RHSCC;
4723 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4724 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4725 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4726 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4727 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4728 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4729 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004730 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4731 // We can't fold (ugt x, C) | (sgt x, C2).
4732 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004733 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004734 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004735 bool NeedsSwap;
4736 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004737 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004738 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004739 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004740
4741 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004742 std::swap(LHS, RHS);
4743 std::swap(LHSCst, RHSCst);
4744 std::swap(LHSCC, RHSCC);
4745 }
4746
Reid Spencere4d87aa2006-12-23 06:05:41 +00004747 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004748 // comparing a value against two constants and or'ing the result
4749 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004750 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4751 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004752 // equal.
4753 assert(LHSCst != RHSCst && "Compares not folded above?");
4754
4755 switch (LHSCC) {
4756 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004757 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004758 switch (RHSCC) {
4759 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004760 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004761 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4762 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004763 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004764 LHSVal->getName()+".off");
4765 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004766 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004767 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004768 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004769 break; // (X == 13 | X == 15) -> no change
4770 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4771 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004772 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004773 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4774 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4775 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004776 return ReplaceInstUsesWith(I, RHS);
4777 }
4778 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004779 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004780 switch (RHSCC) {
4781 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004782 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4783 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4784 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004785 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004786 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4787 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4788 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004789 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004790 }
4791 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004792 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004793 switch (RHSCC) {
4794 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004795 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004796 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004797 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004798 // If RHSCst is [us]MAXINT, it is always false. Not handling
4799 // this can cause overflow.
4800 if (RHSCst->isMaxValue(false))
4801 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004802 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4803 false, I);
4804 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4805 break;
4806 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4807 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004808 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004809 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4810 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004811 }
4812 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004813 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004814 switch (RHSCC) {
4815 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004816 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4817 break;
4818 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004819 // If RHSCst is [us]MAXINT, it is always false. Not handling
4820 // this can cause overflow.
4821 if (RHSCst->isMaxValue(true))
4822 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004823 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4824 false, I);
4825 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4826 break;
4827 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4828 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4829 return ReplaceInstUsesWith(I, RHS);
4830 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4831 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004832 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004833 break;
4834 case ICmpInst::ICMP_UGT:
4835 switch (RHSCC) {
4836 default: assert(0 && "Unknown integer condition code!");
4837 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4838 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4839 return ReplaceInstUsesWith(I, LHS);
4840 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4841 break;
4842 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4843 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004844 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004845 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4846 break;
4847 }
4848 break;
4849 case ICmpInst::ICMP_SGT:
4850 switch (RHSCC) {
4851 default: assert(0 && "Unknown integer condition code!");
4852 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4853 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4854 return ReplaceInstUsesWith(I, LHS);
4855 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4856 break;
4857 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4858 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004859 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004860 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4861 break;
4862 }
4863 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004864 }
4865 }
4866 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004867
4868 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004869 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004870 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004871 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004872 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4873 !isa<ICmpInst>(Op1C->getOperand(0))) {
4874 const Type *SrcTy = Op0C->getOperand(0)->getType();
4875 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4876 // Only do this if the casts both really cause code to be
4877 // generated.
4878 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4879 I.getType(), TD) &&
4880 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4881 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004882 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004883 Op1C->getOperand(0),
4884 I.getName());
4885 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004886 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004887 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004888 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004889 }
Chris Lattner99c65742007-10-24 05:38:08 +00004890 }
4891
4892
4893 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4894 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4895 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4896 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004897 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4898 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004899 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4900 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4901 // If either of the constants are nans, then the whole thing returns
4902 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004903 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004904 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4905
4906 // Otherwise, no need to compare the two constants, compare the
4907 // rest.
4908 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4909 RHS->getOperand(0));
4910 }
4911 }
4912 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004913
Chris Lattner7e708292002-06-25 16:13:24 +00004914 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004915}
4916
Dan Gohman844731a2008-05-13 00:00:25 +00004917namespace {
4918
Chris Lattnerc317d392004-02-16 01:20:27 +00004919// XorSelf - Implements: X ^ X --> 0
4920struct XorSelf {
4921 Value *RHS;
4922 XorSelf(Value *rhs) : RHS(rhs) {}
4923 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4924 Instruction *apply(BinaryOperator &Xor) const {
4925 return &Xor;
4926 }
4927};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004928
Dan Gohman844731a2008-05-13 00:00:25 +00004929}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004930
Chris Lattner7e708292002-06-25 16:13:24 +00004931Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004932 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004933 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004934
Evan Chengd34af782008-03-25 20:07:13 +00004935 if (isa<UndefValue>(Op1)) {
4936 if (isa<UndefValue>(Op0))
4937 // Handle undef ^ undef -> 0 special case. This is a common
4938 // idiom (misuse).
4939 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004940 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004941 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004942
Chris Lattnerc317d392004-02-16 01:20:27 +00004943 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4944 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004945 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004946 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004947 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004948
4949 // See if we can simplify any instructions used by the instruction whose sole
4950 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004951 if (!isa<VectorType>(I.getType())) {
4952 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4953 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4954 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4955 KnownZero, KnownOne))
4956 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004957 } else if (isa<ConstantAggregateZero>(Op1)) {
4958 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004959 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004960
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004961 // Is this a ~ operation?
4962 if (Value *NotOp = dyn_castNotVal(&I)) {
4963 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4964 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4965 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4966 if (Op0I->getOpcode() == Instruction::And ||
4967 Op0I->getOpcode() == Instruction::Or) {
4968 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4969 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4970 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004971 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004972 Op0I->getOperand(1)->getName()+".not");
4973 InsertNewInstBefore(NotY, I);
4974 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004975 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004976 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004977 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004978 }
4979 }
4980 }
4981 }
4982
4983
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004984 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004985 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4986 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4987 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004988 return new ICmpInst(ICI->getInversePredicate(),
4989 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004990
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004991 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4992 return new FCmpInst(FCI->getInversePredicate(),
4993 FCI->getOperand(0), FCI->getOperand(1));
4994 }
4995
Reid Spencere4d87aa2006-12-23 06:05:41 +00004996 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004997 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004998 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4999 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00005000 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5001 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005002 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005003 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005004 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005005
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005006 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005007 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005008 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005009 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00005010 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005011 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00005012 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005013 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00005014 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005015 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005016 // (X + C) ^ signbit -> (X + C + signbit)
5017 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005018 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005019
Chris Lattner7c4049c2004-01-12 19:35:11 +00005020 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005021 } else if (Op0I->getOpcode() == Instruction::Or) {
5022 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005023 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00005024 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5025 // Anything in both C1 and C2 is known to be zero, remove it from
5026 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005027 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005028 NewRHS = ConstantExpr::getAnd(NewRHS,
5029 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005030 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005031 I.setOperand(0, Op0I->getOperand(0));
5032 I.setOperand(1, NewRHS);
5033 return &I;
5034 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005035 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005036 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005037 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005038
5039 // Try to fold constant and into select arguments.
5040 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005041 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005042 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005043 if (isa<PHINode>(Op0))
5044 if (Instruction *NV = FoldOpIntoPhi(I))
5045 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005046 }
5047
Chris Lattner8d969642003-03-10 23:06:50 +00005048 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005049 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005050 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005051
Chris Lattner8d969642003-03-10 23:06:50 +00005052 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005053 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005054 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005055
Chris Lattner318bf792007-03-18 22:51:34 +00005056
5057 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5058 if (Op1I) {
5059 Value *A, *B;
5060 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5061 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005062 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005063 I.swapOperands();
5064 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005065 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005066 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005067 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005068 }
Chris Lattner318bf792007-03-18 22:51:34 +00005069 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5070 if (Op0 == A) // A^(A^B) == B
5071 return ReplaceInstUsesWith(I, B);
5072 else if (Op0 == B) // A^(B^A) == B
5073 return ReplaceInstUsesWith(I, A);
5074 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005075 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005076 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005077 std::swap(A, B);
5078 }
Chris Lattner318bf792007-03-18 22:51:34 +00005079 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005080 I.swapOperands(); // Simplified below.
5081 std::swap(Op0, Op1);
5082 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005083 }
Chris Lattner318bf792007-03-18 22:51:34 +00005084 }
5085
5086 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5087 if (Op0I) {
5088 Value *A, *B;
5089 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5090 if (A == Op1) // (B|A)^B == (A|B)^B
5091 std::swap(A, B);
5092 if (B == Op1) { // (A|B)^B == A & ~B
5093 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005094 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5095 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005096 }
Chris Lattner318bf792007-03-18 22:51:34 +00005097 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5098 if (Op1 == A) // (A^B)^A == B
5099 return ReplaceInstUsesWith(I, B);
5100 else if (Op1 == B) // (B^A)^A == B
5101 return ReplaceInstUsesWith(I, A);
5102 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5103 if (A == Op1) // (A&B)^A -> (B&A)^A
5104 std::swap(A, B);
5105 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005106 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005107 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005108 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5109 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005110 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005111 }
Chris Lattner318bf792007-03-18 22:51:34 +00005112 }
5113
5114 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5115 if (Op0I && Op1I && Op0I->isShift() &&
5116 Op0I->getOpcode() == Op1I->getOpcode() &&
5117 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5118 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5119 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005120 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005121 Op1I->getOperand(0),
5122 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005123 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005124 Op1I->getOperand(1));
5125 }
5126
5127 if (Op0I && Op1I) {
5128 Value *A, *B, *C, *D;
5129 // (A & B)^(A | B) -> A ^ B
5130 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5131 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5132 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005133 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005134 }
5135 // (A | B)^(A & B) -> A ^ B
5136 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5137 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5138 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005139 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005140 }
5141
5142 // (A & B)^(C & D)
5143 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5144 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5145 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5146 // (X & Y)^(X & Y) -> (Y^Z) & X
5147 Value *X = 0, *Y = 0, *Z = 0;
5148 if (A == C)
5149 X = A, Y = B, Z = D;
5150 else if (A == D)
5151 X = A, Y = B, Z = C;
5152 else if (B == C)
5153 X = B, Y = A, Z = D;
5154 else if (B == D)
5155 X = B, Y = A, Z = C;
5156
5157 if (X) {
5158 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005159 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5160 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005161 }
5162 }
5163 }
5164
Reid Spencere4d87aa2006-12-23 06:05:41 +00005165 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5166 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5167 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005168 return R;
5169
Chris Lattner6fc205f2006-05-05 06:39:07 +00005170 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005171 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005172 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005173 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5174 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005175 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005176 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005177 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5178 I.getType(), TD) &&
5179 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5180 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005181 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005182 Op1C->getOperand(0),
5183 I.getName());
5184 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005185 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005186 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005187 }
Chris Lattner99c65742007-10-24 05:38:08 +00005188 }
Chris Lattner7e708292002-06-25 16:13:24 +00005189 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005190}
5191
Chris Lattnera96879a2004-09-29 17:40:11 +00005192/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5193/// overflowed for this type.
5194static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005195 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005196 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005197
Reid Spencere4e40032007-03-21 23:19:50 +00005198 if (IsSigned)
5199 if (In2->getValue().isNegative())
5200 return Result->getValue().sgt(In1->getValue());
5201 else
5202 return Result->getValue().slt(In1->getValue());
5203 else
5204 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005205}
5206
Chris Lattner574da9b2005-01-13 20:14:25 +00005207/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5208/// code necessary to compute the offset from the base pointer (without adding
5209/// in the base pointer). Return the result as a signed integer of intptr size.
5210static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5211 TargetData &TD = IC.getTargetData();
5212 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005213 const Type *IntPtrTy = TD.getIntPtrType();
5214 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005215
5216 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005217 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005218 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005219
Chris Lattner574da9b2005-01-13 20:14:25 +00005220 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5221 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00005222 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005223 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5224 if (OpC->isZero()) continue;
5225
5226 // Handle a struct index, which adds its field offset to the pointer.
5227 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5228 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5229
5230 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5231 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005232 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005233 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005234 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005235 ConstantInt::get(IntPtrTy, Size),
5236 GEP->getName()+".offs"), I);
5237 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005238 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005239
5240 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5241 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5242 Scale = ConstantExpr::getMul(OC, Scale);
5243 if (Constant *RC = dyn_cast<Constant>(Result))
5244 Result = ConstantExpr::getAdd(RC, Scale);
5245 else {
5246 // Emit an add instruction.
5247 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005248 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005249 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005250 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005251 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005252 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005253 // Convert to correct type.
5254 if (Op->getType() != IntPtrTy) {
5255 if (Constant *OpC = dyn_cast<Constant>(Op))
5256 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5257 else
5258 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5259 Op->getName()+".c"), I);
5260 }
5261 if (Size != 1) {
5262 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5263 if (Constant *OpC = dyn_cast<Constant>(Op))
5264 Op = ConstantExpr::getMul(OpC, Scale);
5265 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005266 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005267 GEP->getName()+".idx"), I);
5268 }
5269
5270 // Emit an add instruction.
5271 if (isa<Constant>(Op) && isa<Constant>(Result))
5272 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5273 cast<Constant>(Result));
5274 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005275 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005276 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005277 }
5278 return Result;
5279}
5280
Chris Lattner10c0d912008-04-22 02:53:33 +00005281
5282/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5283/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5284/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5285/// complex, and scales are involved. The above expression would also be legal
5286/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5287/// later form is less amenable to optimization though, and we are allowed to
5288/// generate the first by knowing that pointer arithmetic doesn't overflow.
5289///
5290/// If we can't emit an optimized form for this expression, this returns null.
5291///
5292static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5293 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005294 TargetData &TD = IC.getTargetData();
5295 gep_type_iterator GTI = gep_type_begin(GEP);
5296
5297 // Check to see if this gep only has a single variable index. If so, and if
5298 // any constant indices are a multiple of its scale, then we can compute this
5299 // in terms of the scale of the variable index. For example, if the GEP
5300 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5301 // because the expression will cross zero at the same point.
5302 unsigned i, e = GEP->getNumOperands();
5303 int64_t Offset = 0;
5304 for (i = 1; i != e; ++i, ++GTI) {
5305 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5306 // Compute the aggregate offset of constant indices.
5307 if (CI->isZero()) continue;
5308
5309 // Handle a struct index, which adds its field offset to the pointer.
5310 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5311 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5312 } else {
5313 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5314 Offset += Size*CI->getSExtValue();
5315 }
5316 } else {
5317 // Found our variable index.
5318 break;
5319 }
5320 }
5321
5322 // If there are no variable indices, we must have a constant offset, just
5323 // evaluate it the general way.
5324 if (i == e) return 0;
5325
5326 Value *VariableIdx = GEP->getOperand(i);
5327 // Determine the scale factor of the variable element. For example, this is
5328 // 4 if the variable index is into an array of i32.
5329 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5330
5331 // Verify that there are no other variable indices. If so, emit the hard way.
5332 for (++i, ++GTI; i != e; ++i, ++GTI) {
5333 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5334 if (!CI) return 0;
5335
5336 // Compute the aggregate offset of constant indices.
5337 if (CI->isZero()) continue;
5338
5339 // Handle a struct index, which adds its field offset to the pointer.
5340 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5341 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5342 } else {
5343 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5344 Offset += Size*CI->getSExtValue();
5345 }
5346 }
5347
5348 // Okay, we know we have a single variable index, which must be a
5349 // pointer/array/vector index. If there is no offset, life is simple, return
5350 // the index.
5351 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5352 if (Offset == 0) {
5353 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5354 // we don't need to bother extending: the extension won't affect where the
5355 // computation crosses zero.
5356 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5357 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5358 VariableIdx->getNameStart(), &I);
5359 return VariableIdx;
5360 }
5361
5362 // Otherwise, there is an index. The computation we will do will be modulo
5363 // the pointer size, so get it.
5364 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5365
5366 Offset &= PtrSizeMask;
5367 VariableScale &= PtrSizeMask;
5368
5369 // To do this transformation, any constant index must be a multiple of the
5370 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5371 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5372 // multiple of the variable scale.
5373 int64_t NewOffs = Offset / (int64_t)VariableScale;
5374 if (Offset != NewOffs*(int64_t)VariableScale)
5375 return 0;
5376
5377 // Okay, we can do this evaluation. Start by converting the index to intptr.
5378 const Type *IntPtrTy = TD.getIntPtrType();
5379 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005380 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005381 true /*SExt*/,
5382 VariableIdx->getNameStart(), &I);
5383 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005384 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005385}
5386
5387
Reid Spencere4d87aa2006-12-23 06:05:41 +00005388/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005389/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005390Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5391 ICmpInst::Predicate Cond,
5392 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005393 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005394
Chris Lattner10c0d912008-04-22 02:53:33 +00005395 // Look through bitcasts.
5396 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5397 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005398
Chris Lattner574da9b2005-01-13 20:14:25 +00005399 Value *PtrBase = GEPLHS->getOperand(0);
5400 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005401 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005402 // This transformation (ignoring the base and scales) is valid because we
5403 // know pointers can't overflow. See if we can output an optimized form.
5404 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5405
5406 // If not, synthesize the offset the hard way.
5407 if (Offset == 0)
5408 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005409 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5410 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005411 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005412 // If the base pointers are different, but the indices are the same, just
5413 // compare the base pointer.
5414 if (PtrBase != GEPRHS->getOperand(0)) {
5415 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005416 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005417 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005418 if (IndicesTheSame)
5419 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5420 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5421 IndicesTheSame = false;
5422 break;
5423 }
5424
5425 // If all indices are the same, just compare the base pointers.
5426 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005427 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5428 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005429
5430 // Otherwise, the base pointers are different and the indices are
5431 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005432 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005433 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005434
Chris Lattnere9d782b2005-01-13 22:25:21 +00005435 // If one of the GEPs has all zero indices, recurse.
5436 bool AllZeros = true;
5437 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5438 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5439 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5440 AllZeros = false;
5441 break;
5442 }
5443 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005444 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5445 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005446
5447 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005448 AllZeros = true;
5449 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5450 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5451 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5452 AllZeros = false;
5453 break;
5454 }
5455 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005456 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005457
Chris Lattner4401c9c2005-01-14 00:20:05 +00005458 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5459 // If the GEPs only differ by one index, compare it.
5460 unsigned NumDifferences = 0; // Keep track of # differences.
5461 unsigned DiffOperand = 0; // The operand that differs.
5462 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5463 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005464 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5465 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005466 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005467 NumDifferences = 2;
5468 break;
5469 } else {
5470 if (NumDifferences++) break;
5471 DiffOperand = i;
5472 }
5473 }
5474
5475 if (NumDifferences == 0) // SAME GEP?
5476 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005477 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005478 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005479
Chris Lattner4401c9c2005-01-14 00:20:05 +00005480 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005481 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5482 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005483 // Make sure we do a signed comparison here.
5484 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005485 }
5486 }
5487
Reid Spencere4d87aa2006-12-23 06:05:41 +00005488 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005489 // the result to fold to a constant!
5490 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5491 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5492 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5493 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5494 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005495 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005496 }
5497 }
5498 return 0;
5499}
5500
Chris Lattnera5406232008-05-19 20:18:56 +00005501/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5502///
5503Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5504 Instruction *LHSI,
5505 Constant *RHSC) {
5506 if (!isa<ConstantFP>(RHSC)) return 0;
5507 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5508
5509 // Get the width of the mantissa. We don't want to hack on conversions that
5510 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005511 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005512 if (MantissaWidth == -1) return 0; // Unknown.
5513
5514 // Check to see that the input is converted from an integer type that is small
5515 // enough that preserves all bits. TODO: check here for "known" sign bits.
5516 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5517 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5518
5519 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5520 if (isa<UIToFPInst>(LHSI))
5521 ++InputSize;
5522
5523 // If the conversion would lose info, don't hack on this.
5524 if ((int)InputSize > MantissaWidth)
5525 return 0;
5526
5527 // Otherwise, we can potentially simplify the comparison. We know that it
5528 // will always come through as an integer value and we know the constant is
5529 // not a NAN (it would have been previously simplified).
5530 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5531
5532 ICmpInst::Predicate Pred;
5533 switch (I.getPredicate()) {
5534 default: assert(0 && "Unexpected predicate!");
5535 case FCmpInst::FCMP_UEQ:
5536 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5537 case FCmpInst::FCMP_UGT:
5538 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5539 case FCmpInst::FCMP_UGE:
5540 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5541 case FCmpInst::FCMP_ULT:
5542 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5543 case FCmpInst::FCMP_ULE:
5544 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5545 case FCmpInst::FCMP_UNE:
5546 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5547 case FCmpInst::FCMP_ORD:
5548 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5549 case FCmpInst::FCMP_UNO:
5550 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5551 }
5552
5553 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5554
5555 // Now we know that the APFloat is a normal number, zero or inf.
5556
Chris Lattner85162782008-05-20 03:50:52 +00005557 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005558 // comparing an i8 to 300.0.
5559 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5560
5561 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5562 // and large values.
5563 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5564 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5565 APFloat::rmNearestTiesToEven);
5566 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5567 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5568 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5569 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5570 }
5571
5572 // See if the RHS value is < SignedMin.
5573 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5574 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5575 APFloat::rmNearestTiesToEven);
5576 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5577 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5578 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5579 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5580 }
5581
5582 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5583 // it may still be fractional. See if it is fractional by casting the FP
5584 // value to the integer value and back, checking for equality. Don't do this
5585 // for zero, because -0.0 is not fractional.
5586 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5587 if (!RHS.isZero() &&
5588 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5589 // If we had a comparison against a fractional value, we have to adjust
5590 // the compare predicate and sometimes the value. RHSC is rounded towards
5591 // zero at this point.
5592 switch (Pred) {
5593 default: assert(0 && "Unexpected integer comparison!");
5594 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5595 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5596 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5597 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5598 case ICmpInst::ICMP_SLE:
5599 // (float)int <= 4.4 --> int <= 4
5600 // (float)int <= -4.4 --> int < -4
5601 if (RHS.isNegative())
5602 Pred = ICmpInst::ICMP_SLT;
5603 break;
5604 case ICmpInst::ICMP_SLT:
5605 // (float)int < -4.4 --> int < -4
5606 // (float)int < 4.4 --> int <= 4
5607 if (!RHS.isNegative())
5608 Pred = ICmpInst::ICMP_SLE;
5609 break;
5610 case ICmpInst::ICMP_SGT:
5611 // (float)int > 4.4 --> int > 4
5612 // (float)int > -4.4 --> int >= -4
5613 if (RHS.isNegative())
5614 Pred = ICmpInst::ICMP_SGE;
5615 break;
5616 case ICmpInst::ICMP_SGE:
5617 // (float)int >= -4.4 --> int >= -4
5618 // (float)int >= 4.4 --> int > 4
5619 if (!RHS.isNegative())
5620 Pred = ICmpInst::ICMP_SGT;
5621 break;
5622 }
5623 }
5624
5625 // Lower this FP comparison into an appropriate integer version of the
5626 // comparison.
5627 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5628}
5629
Reid Spencere4d87aa2006-12-23 06:05:41 +00005630Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5631 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005632 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005633
Chris Lattner58e97462007-01-14 19:42:17 +00005634 // Fold trivial predicates.
5635 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5636 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5637 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5638 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5639
5640 // Simplify 'fcmp pred X, X'
5641 if (Op0 == Op1) {
5642 switch (I.getPredicate()) {
5643 default: assert(0 && "Unknown predicate!");
5644 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5645 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5646 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5647 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5648 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5649 case FCmpInst::FCMP_OLT: // True if ordered and less than
5650 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5651 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5652
5653 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5654 case FCmpInst::FCMP_ULT: // True if unordered or less than
5655 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5656 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5657 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5658 I.setPredicate(FCmpInst::FCMP_UNO);
5659 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5660 return &I;
5661
5662 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5663 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5664 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5665 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5666 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5667 I.setPredicate(FCmpInst::FCMP_ORD);
5668 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5669 return &I;
5670 }
5671 }
5672
Reid Spencere4d87aa2006-12-23 06:05:41 +00005673 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005674 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005675
Reid Spencere4d87aa2006-12-23 06:05:41 +00005676 // Handle fcmp with constant RHS
5677 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005678 // If the constant is a nan, see if we can fold the comparison based on it.
5679 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5680 if (CFP->getValueAPF().isNaN()) {
5681 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5682 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005683 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5684 "Comparison must be either ordered or unordered!");
5685 // True if unordered.
5686 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005687 }
5688 }
5689
Reid Spencere4d87aa2006-12-23 06:05:41 +00005690 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5691 switch (LHSI->getOpcode()) {
5692 case Instruction::PHI:
5693 if (Instruction *NV = FoldOpIntoPhi(I))
5694 return NV;
5695 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005696 case Instruction::SIToFP:
5697 case Instruction::UIToFP:
5698 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5699 return NV;
5700 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005701 case Instruction::Select:
5702 // If either operand of the select is a constant, we can fold the
5703 // comparison into the select arms, which will cause one to be
5704 // constant folded and the select turned into a bitwise or.
5705 Value *Op1 = 0, *Op2 = 0;
5706 if (LHSI->hasOneUse()) {
5707 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5708 // Fold the known value into the constant operand.
5709 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5710 // Insert a new FCmp of the other select operand.
5711 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5712 LHSI->getOperand(2), RHSC,
5713 I.getName()), I);
5714 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5715 // Fold the known value into the constant operand.
5716 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5717 // Insert a new FCmp of the other select operand.
5718 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5719 LHSI->getOperand(1), RHSC,
5720 I.getName()), I);
5721 }
5722 }
5723
5724 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005725 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005726 break;
5727 }
5728 }
5729
5730 return Changed ? &I : 0;
5731}
5732
5733Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5734 bool Changed = SimplifyCompare(I);
5735 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5736 const Type *Ty = Op0->getType();
5737
5738 // icmp X, X
5739 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005740 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005741 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005742
5743 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005744 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005745
Reid Spencere4d87aa2006-12-23 06:05:41 +00005746 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005747 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005748 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5749 isa<ConstantPointerNull>(Op0)) &&
5750 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005751 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005752 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005753 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005754
Reid Spencere4d87aa2006-12-23 06:05:41 +00005755 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005756 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005757 switch (I.getPredicate()) {
5758 default: assert(0 && "Invalid icmp instruction!");
5759 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005760 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005761 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005762 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005763 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005764 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005765 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005766
Reid Spencere4d87aa2006-12-23 06:05:41 +00005767 case ICmpInst::ICMP_UGT:
5768 case ICmpInst::ICMP_SGT:
5769 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005770 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005771 case ICmpInst::ICMP_ULT:
5772 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005773 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005774 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005775 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005776 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005777 case ICmpInst::ICMP_UGE:
5778 case ICmpInst::ICMP_SGE:
5779 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005780 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005781 case ICmpInst::ICMP_ULE:
5782 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005783 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005784 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005785 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005786 }
5787 }
Chris Lattner8b170942002-08-09 23:47:40 +00005788 }
5789
Chris Lattner2be51ae2004-06-09 04:24:29 +00005790 // See if we are doing a comparison between a constant and an instruction that
5791 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005792 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005793 Value *A, *B;
5794
Chris Lattnerb6566012008-01-05 01:18:20 +00005795 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5796 if (I.isEquality() && CI->isNullValue() &&
5797 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5798 // (icmp cond A B) if cond is equality
5799 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005800 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005801
Reid Spencere4d87aa2006-12-23 06:05:41 +00005802 switch (I.getPredicate()) {
5803 default: break;
5804 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5805 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005806 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005807 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5808 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5809 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5810 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005811 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5812 if (CI->isMinValue(true))
5813 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5814 ConstantInt::getAllOnesValue(Op0->getType()));
5815
Reid Spencere4d87aa2006-12-23 06:05:41 +00005816 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005817
Reid Spencere4d87aa2006-12-23 06:05:41 +00005818 case ICmpInst::ICMP_SLT:
5819 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005820 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005821 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5822 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5823 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5824 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5825 break;
5826
5827 case ICmpInst::ICMP_UGT:
5828 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005829 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005830 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5831 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5832 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5833 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005834
5835 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5836 if (CI->isMaxValue(true))
5837 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5838 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005839 break;
5840
5841 case ICmpInst::ICMP_SGT:
5842 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005843 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005844 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5845 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5846 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5847 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5848 break;
5849
5850 case ICmpInst::ICMP_ULE:
5851 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005852 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005853 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5854 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5855 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5856 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5857 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005858
Reid Spencere4d87aa2006-12-23 06:05:41 +00005859 case ICmpInst::ICMP_SLE:
5860 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005861 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005862 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5863 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5864 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5865 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5866 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005867
Reid Spencere4d87aa2006-12-23 06:05:41 +00005868 case ICmpInst::ICMP_UGE:
5869 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005870 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005871 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5872 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5873 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5874 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5875 break;
5876
5877 case ICmpInst::ICMP_SGE:
5878 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005879 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005880 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5881 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5882 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5883 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5884 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005885 }
5886
Reid Spencere4d87aa2006-12-23 06:05:41 +00005887 // If we still have a icmp le or icmp ge instruction, turn it into the
5888 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005889 // already been handled above, this requires little checking.
5890 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005891 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005892 default: break;
5893 case ICmpInst::ICMP_ULE:
5894 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5895 case ICmpInst::ICMP_SLE:
5896 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5897 case ICmpInst::ICMP_UGE:
5898 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5899 case ICmpInst::ICMP_SGE:
5900 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005901 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005902
5903 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005904 // in the input. If this comparison is a normal comparison, it demands all
5905 // bits, if it is a sign bit comparison, it only demands the sign bit.
5906
5907 bool UnusedBit;
5908 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5909
Reid Spencer0460fb32007-03-22 20:36:03 +00005910 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5911 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005912 if (SimplifyDemandedBits(Op0,
5913 isSignBit ? APInt::getSignBit(BitWidth)
5914 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005915 KnownZero, KnownOne, 0))
5916 return &I;
5917
5918 // Given the known and unknown bits, compute a range that the LHS could be
5919 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005920 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005921 // Compute the Min, Max and RHS values based on the known bits. For the
5922 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005923 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5924 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005925 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005926 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5927 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005928 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005929 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5930 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005931 }
5932 switch (I.getPredicate()) { // LE/GE have been folded already.
5933 default: assert(0 && "Unknown icmp opcode!");
5934 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005935 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005936 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005937 break;
5938 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005939 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005940 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005941 break;
5942 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005943 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005944 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005945 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005946 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005947 break;
5948 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005949 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005950 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005951 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005952 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005953 break;
5954 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005955 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005956 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005957 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005958 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005959 break;
5960 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005961 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005962 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005963 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005964 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005965 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005966 }
5967 }
5968
Reid Spencere4d87aa2006-12-23 06:05:41 +00005969 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005970 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005971 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005972 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005973 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5974 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005975 }
5976
Chris Lattner01deb9d2007-04-03 17:43:25 +00005977 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005978 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5979 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5980 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005981 case Instruction::GetElementPtr:
5982 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005983 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005984 bool isAllZeros = true;
5985 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5986 if (!isa<Constant>(LHSI->getOperand(i)) ||
5987 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5988 isAllZeros = false;
5989 break;
5990 }
5991 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005992 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005993 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5994 }
5995 break;
5996
Chris Lattner6970b662005-04-23 15:31:55 +00005997 case Instruction::PHI:
5998 if (Instruction *NV = FoldOpIntoPhi(I))
5999 return NV;
6000 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006001 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006002 // If either operand of the select is a constant, we can fold the
6003 // comparison into the select arms, which will cause one to be
6004 // constant folded and the select turned into a bitwise or.
6005 Value *Op1 = 0, *Op2 = 0;
6006 if (LHSI->hasOneUse()) {
6007 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6008 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006009 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6010 // Insert a new ICmp of the other select operand.
6011 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6012 LHSI->getOperand(2), RHSC,
6013 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006014 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6015 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006016 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6017 // Insert a new ICmp of the other select operand.
6018 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6019 LHSI->getOperand(1), RHSC,
6020 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006021 }
6022 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006023
Chris Lattner6970b662005-04-23 15:31:55 +00006024 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006025 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006026 break;
6027 }
Chris Lattner4802d902007-04-06 18:57:34 +00006028 case Instruction::Malloc:
6029 // If we have (malloc != null), and if the malloc has a single use, we
6030 // can assume it is successful and remove the malloc.
6031 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6032 AddToWorkList(LHSI);
6033 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006034 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006035 }
6036 break;
6037 }
Chris Lattner6970b662005-04-23 15:31:55 +00006038 }
6039
Reid Spencere4d87aa2006-12-23 06:05:41 +00006040 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006041 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006042 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006043 return NI;
6044 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006045 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6046 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006047 return NI;
6048
Reid Spencere4d87aa2006-12-23 06:05:41 +00006049 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006050 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6051 // now.
6052 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6053 if (isa<PointerType>(Op0->getType()) &&
6054 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006055 // We keep moving the cast from the left operand over to the right
6056 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006057 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006058
Chris Lattner57d86372007-01-06 01:45:59 +00006059 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6060 // so eliminate it as well.
6061 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6062 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006063
Chris Lattnerde90b762003-11-03 04:25:02 +00006064 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006065 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006066 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006067 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006068 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006069 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006070 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006071 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006072 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006073 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006074 }
Chris Lattner57d86372007-01-06 01:45:59 +00006075 }
6076
6077 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006078 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006079 // This comes up when you have code like
6080 // int X = A < B;
6081 // if (X) ...
6082 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006083 // with a constant or another cast from the same type.
6084 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006085 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006086 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006087 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006088
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006089 // ~x < ~y --> y < x
6090 { Value *A, *B;
6091 if (match(Op0, m_Not(m_Value(A))) &&
6092 match(Op1, m_Not(m_Value(B))))
6093 return new ICmpInst(I.getPredicate(), B, A);
6094 }
6095
Chris Lattner65b72ba2006-09-18 04:22:48 +00006096 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006097 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006098
6099 // -x == -y --> x == y
6100 if (match(Op0, m_Neg(m_Value(A))) &&
6101 match(Op1, m_Neg(m_Value(B))))
6102 return new ICmpInst(I.getPredicate(), A, B);
6103
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006104 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6105 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6106 Value *OtherVal = A == Op1 ? B : A;
6107 return new ICmpInst(I.getPredicate(), OtherVal,
6108 Constant::getNullValue(A->getType()));
6109 }
6110
6111 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6112 // A^c1 == C^c2 --> A == C^(c1^c2)
6113 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6114 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6115 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006116 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006117 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006118 return new ICmpInst(I.getPredicate(), A,
6119 InsertNewInstBefore(Xor, I));
6120 }
6121
6122 // A^B == A^D -> B == D
6123 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6124 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6125 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6126 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6127 }
6128 }
6129
6130 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6131 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006132 // A == (A^B) -> B == 0
6133 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006134 return new ICmpInst(I.getPredicate(), OtherVal,
6135 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006136 }
6137 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006138 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006139 return new ICmpInst(I.getPredicate(), B,
6140 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006141 }
6142 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006143 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006144 return new ICmpInst(I.getPredicate(), B,
6145 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00006146 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00006147
Chris Lattner9c2328e2006-11-14 06:06:06 +00006148 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6149 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6150 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6151 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6152 Value *X = 0, *Y = 0, *Z = 0;
6153
6154 if (A == C) {
6155 X = B; Y = D; Z = A;
6156 } else if (A == D) {
6157 X = B; Y = C; Z = A;
6158 } else if (B == C) {
6159 X = A; Y = D; Z = B;
6160 } else if (B == D) {
6161 X = A; Y = C; Z = B;
6162 }
6163
6164 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006165 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6166 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006167 I.setOperand(0, Op1);
6168 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6169 return &I;
6170 }
6171 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006172 }
Chris Lattner7e708292002-06-25 16:13:24 +00006173 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006174}
6175
Chris Lattner562ef782007-06-20 23:46:26 +00006176
6177/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6178/// and CmpRHS are both known to be integer constants.
6179Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6180 ConstantInt *DivRHS) {
6181 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6182 const APInt &CmpRHSV = CmpRHS->getValue();
6183
6184 // FIXME: If the operand types don't match the type of the divide
6185 // then don't attempt this transform. The code below doesn't have the
6186 // logic to deal with a signed divide and an unsigned compare (and
6187 // vice versa). This is because (x /s C1) <s C2 produces different
6188 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6189 // (x /u C1) <u C2. Simply casting the operands and result won't
6190 // work. :( The if statement below tests that condition and bails
6191 // if it finds it.
6192 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6193 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6194 return 0;
6195 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006196 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00006197
6198 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6199 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6200 // C2 (CI). By solving for X we can turn this into a range check
6201 // instead of computing a divide.
6202 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6203
6204 // Determine if the product overflows by seeing if the product is
6205 // not equal to the divide. Make sure we do the same kind of divide
6206 // as in the LHS instruction that we're folding.
6207 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6208 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6209
6210 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006211 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006212
Chris Lattner1dbfd482007-06-21 18:11:19 +00006213 // Figure out the interval that is being checked. For example, a comparison
6214 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6215 // Compute this interval based on the constants involved and the signedness of
6216 // the compare/divide. This computes a half-open interval, keeping track of
6217 // whether either value in the interval overflows. After analysis each
6218 // overflow variable is set to 0 if it's corresponding bound variable is valid
6219 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6220 int LoOverflow = 0, HiOverflow = 0;
6221 ConstantInt *LoBound = 0, *HiBound = 0;
6222
6223
Chris Lattner562ef782007-06-20 23:46:26 +00006224 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006225 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006226 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006227 HiOverflow = LoOverflow = ProdOV;
6228 if (!HiOverflow)
6229 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006230 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006231 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006232 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006233 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6234 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006235 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006236 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6237 HiOverflow = LoOverflow = ProdOV;
6238 if (!HiOverflow)
6239 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006240 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006241 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006242 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6243 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00006244 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006245 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006246 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006247 }
Dan Gohman76491272008-02-13 22:09:18 +00006248 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006249 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006250 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006251 LoBound = AddOne(DivRHS);
6252 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006253 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6254 HiOverflow = 1; // [INTMIN+1, overflow)
6255 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6256 }
Dan Gohman76491272008-02-13 22:09:18 +00006257 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006258 // e.g. X/-5 op 3 --> [-19, -14)
6259 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006260 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006261 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00006262 HiBound = AddOne(Prod);
6263 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006264 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006265 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006266 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006267 HiBound = Subtract(Prod, DivRHS);
6268 }
6269
Chris Lattner1dbfd482007-06-21 18:11:19 +00006270 // Dividing by a negative swaps the condition. LT <-> GT
6271 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006272 }
6273
6274 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006275 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006276 default: assert(0 && "Unhandled icmp opcode!");
6277 case ICmpInst::ICMP_EQ:
6278 if (LoOverflow && HiOverflow)
6279 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6280 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006281 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006282 ICmpInst::ICMP_UGE, X, LoBound);
6283 else if (LoOverflow)
6284 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6285 ICmpInst::ICMP_ULT, X, HiBound);
6286 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006287 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006288 case ICmpInst::ICMP_NE:
6289 if (LoOverflow && HiOverflow)
6290 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6291 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006292 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006293 ICmpInst::ICMP_ULT, X, LoBound);
6294 else if (LoOverflow)
6295 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6296 ICmpInst::ICMP_UGE, X, HiBound);
6297 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006298 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006299 case ICmpInst::ICMP_ULT:
6300 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006301 if (LoOverflow == +1) // Low bound is greater than input range.
6302 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6303 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006304 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006305 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006306 case ICmpInst::ICMP_UGT:
6307 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006308 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006309 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006310 else if (HiOverflow == -1) // High bound less than input range.
6311 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6312 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006313 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6314 else
6315 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6316 }
6317}
6318
6319
Chris Lattner01deb9d2007-04-03 17:43:25 +00006320/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6321///
6322Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6323 Instruction *LHSI,
6324 ConstantInt *RHS) {
6325 const APInt &RHSV = RHS->getValue();
6326
6327 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00006328 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006329 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6330 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6331 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006332 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6333 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006334 Value *CompareVal = LHSI->getOperand(0);
6335
6336 // If the sign bit of the XorCST is not set, there is no change to
6337 // the operation, just stop using the Xor.
6338 if (!XorCST->getValue().isNegative()) {
6339 ICI.setOperand(0, CompareVal);
6340 AddToWorkList(LHSI);
6341 return &ICI;
6342 }
6343
6344 // Was the old condition true if the operand is positive?
6345 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6346
6347 // If so, the new one isn't.
6348 isTrueIfPositive ^= true;
6349
6350 if (isTrueIfPositive)
6351 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6352 else
6353 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6354 }
6355 }
6356 break;
6357 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6358 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6359 LHSI->getOperand(0)->hasOneUse()) {
6360 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6361
6362 // If the LHS is an AND of a truncating cast, we can widen the
6363 // and/compare to be the input width without changing the value
6364 // produced, eliminating a cast.
6365 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6366 // We can do this transformation if either the AND constant does not
6367 // have its sign bit set or if it is an equality comparison.
6368 // Extending a relational comparison when we're checking the sign
6369 // bit would not work.
6370 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006371 (ICI.isEquality() ||
6372 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006373 uint32_t BitWidth =
6374 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6375 APInt NewCST = AndCST->getValue();
6376 NewCST.zext(BitWidth);
6377 APInt NewCI = RHSV;
6378 NewCI.zext(BitWidth);
6379 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006380 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006381 ConstantInt::get(NewCST),LHSI->getName());
6382 InsertNewInstBefore(NewAnd, ICI);
6383 return new ICmpInst(ICI.getPredicate(), NewAnd,
6384 ConstantInt::get(NewCI));
6385 }
6386 }
6387
6388 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6389 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6390 // happens a LOT in code produced by the C front-end, for bitfield
6391 // access.
6392 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6393 if (Shift && !Shift->isShift())
6394 Shift = 0;
6395
6396 ConstantInt *ShAmt;
6397 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6398 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6399 const Type *AndTy = AndCST->getType(); // Type of the and.
6400
6401 // We can fold this as long as we can't shift unknown bits
6402 // into the mask. This can only happen with signed shift
6403 // rights, as they sign-extend.
6404 if (ShAmt) {
6405 bool CanFold = Shift->isLogicalShift();
6406 if (!CanFold) {
6407 // To test for the bad case of the signed shr, see if any
6408 // of the bits shifted in could be tested after the mask.
6409 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6410 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6411
6412 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6413 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6414 AndCST->getValue()) == 0)
6415 CanFold = true;
6416 }
6417
6418 if (CanFold) {
6419 Constant *NewCst;
6420 if (Shift->getOpcode() == Instruction::Shl)
6421 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6422 else
6423 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6424
6425 // Check to see if we are shifting out any of the bits being
6426 // compared.
6427 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6428 // If we shifted bits out, the fold is not going to work out.
6429 // As a special case, check to see if this means that the
6430 // result is always true or false now.
6431 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6432 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6433 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6434 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6435 } else {
6436 ICI.setOperand(1, NewCst);
6437 Constant *NewAndCST;
6438 if (Shift->getOpcode() == Instruction::Shl)
6439 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6440 else
6441 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6442 LHSI->setOperand(1, NewAndCST);
6443 LHSI->setOperand(0, Shift->getOperand(0));
6444 AddToWorkList(Shift); // Shift is dead.
6445 AddUsesToWorkList(ICI);
6446 return &ICI;
6447 }
6448 }
6449 }
6450
6451 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6452 // preferable because it allows the C<<Y expression to be hoisted out
6453 // of a loop if Y is invariant and X is not.
6454 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6455 ICI.isEquality() && !Shift->isArithmeticShift() &&
6456 isa<Instruction>(Shift->getOperand(0))) {
6457 // Compute C << Y.
6458 Value *NS;
6459 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006460 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006461 Shift->getOperand(1), "tmp");
6462 } else {
6463 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006464 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006465 Shift->getOperand(1), "tmp");
6466 }
6467 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6468
6469 // Compute X & (C << Y).
6470 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006471 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006472 InsertNewInstBefore(NewAnd, ICI);
6473
6474 ICI.setOperand(0, NewAnd);
6475 return &ICI;
6476 }
6477 }
6478 break;
6479
Chris Lattnera0141b92007-07-15 20:42:37 +00006480 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6481 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6482 if (!ShAmt) break;
6483
6484 uint32_t TypeBits = RHSV.getBitWidth();
6485
6486 // Check that the shift amount is in range. If not, don't perform
6487 // undefined shifts. When the shift is visited it will be
6488 // simplified.
6489 if (ShAmt->uge(TypeBits))
6490 break;
6491
6492 if (ICI.isEquality()) {
6493 // If we are comparing against bits always shifted out, the
6494 // comparison cannot succeed.
6495 Constant *Comp =
6496 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6497 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6498 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6499 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6500 return ReplaceInstUsesWith(ICI, Cst);
6501 }
6502
6503 if (LHSI->hasOneUse()) {
6504 // Otherwise strength reduce the shift into an and.
6505 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6506 Constant *Mask =
6507 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006508
Chris Lattnera0141b92007-07-15 20:42:37 +00006509 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006510 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006511 Mask, LHSI->getName()+".mask");
6512 Value *And = InsertNewInstBefore(AndI, ICI);
6513 return new ICmpInst(ICI.getPredicate(), And,
6514 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006515 }
6516 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006517
6518 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6519 bool TrueIfSigned = false;
6520 if (LHSI->hasOneUse() &&
6521 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6522 // (X << 31) <s 0 --> (X&1) != 0
6523 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6524 (TypeBits-ShAmt->getZExtValue()-1));
6525 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006526 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006527 Mask, LHSI->getName()+".mask");
6528 Value *And = InsertNewInstBefore(AndI, ICI);
6529
6530 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6531 And, Constant::getNullValue(And->getType()));
6532 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006533 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006534 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006535
6536 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006537 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006538 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006539 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006540 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006541
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006542 // Check that the shift amount is in range. If not, don't perform
6543 // undefined shifts. When the shift is visited it will be
6544 // simplified.
6545 uint32_t TypeBits = RHSV.getBitWidth();
6546 if (ShAmt->uge(TypeBits))
6547 break;
6548
6549 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006550
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006551 // If we are comparing against bits always shifted out, the
6552 // comparison cannot succeed.
6553 APInt Comp = RHSV << ShAmtVal;
6554 if (LHSI->getOpcode() == Instruction::LShr)
6555 Comp = Comp.lshr(ShAmtVal);
6556 else
6557 Comp = Comp.ashr(ShAmtVal);
6558
6559 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6560 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6561 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6562 return ReplaceInstUsesWith(ICI, Cst);
6563 }
6564
6565 // Otherwise, check to see if the bits shifted out are known to be zero.
6566 // If so, we can compare against the unshifted value:
6567 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006568 if (LHSI->hasOneUse() &&
6569 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006570 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6571 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6572 ConstantExpr::getShl(RHS, ShAmt));
6573 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006574
Evan Chengf30752c2008-04-23 00:38:06 +00006575 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006576 // Otherwise strength reduce the shift into an and.
6577 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6578 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006579
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006580 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006581 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006582 Mask, LHSI->getName()+".mask");
6583 Value *And = InsertNewInstBefore(AndI, ICI);
6584 return new ICmpInst(ICI.getPredicate(), And,
6585 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006586 }
6587 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006588 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006589
6590 case Instruction::SDiv:
6591 case Instruction::UDiv:
6592 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6593 // Fold this div into the comparison, producing a range check.
6594 // Determine, based on the divide type, what the range is being
6595 // checked. If there is an overflow on the low or high side, remember
6596 // it, otherwise compute the range [low, hi) bounding the new value.
6597 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006598 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6599 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6600 DivRHS))
6601 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006602 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006603
6604 case Instruction::Add:
6605 // Fold: icmp pred (add, X, C1), C2
6606
6607 if (!ICI.isEquality()) {
6608 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6609 if (!LHSC) break;
6610 const APInt &LHSV = LHSC->getValue();
6611
6612 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6613 .subtract(LHSV);
6614
6615 if (ICI.isSignedPredicate()) {
6616 if (CR.getLower().isSignBit()) {
6617 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6618 ConstantInt::get(CR.getUpper()));
6619 } else if (CR.getUpper().isSignBit()) {
6620 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6621 ConstantInt::get(CR.getLower()));
6622 }
6623 } else {
6624 if (CR.getLower().isMinValue()) {
6625 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6626 ConstantInt::get(CR.getUpper()));
6627 } else if (CR.getUpper().isMinValue()) {
6628 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6629 ConstantInt::get(CR.getLower()));
6630 }
6631 }
6632 }
6633 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006634 }
6635
6636 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6637 if (ICI.isEquality()) {
6638 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6639
6640 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6641 // the second operand is a constant, simplify a bit.
6642 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6643 switch (BO->getOpcode()) {
6644 case Instruction::SRem:
6645 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6646 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6647 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6648 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6649 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006650 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006651 BO->getName());
6652 InsertNewInstBefore(NewRem, ICI);
6653 return new ICmpInst(ICI.getPredicate(), NewRem,
6654 Constant::getNullValue(BO->getType()));
6655 }
6656 }
6657 break;
6658 case Instruction::Add:
6659 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6660 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6661 if (BO->hasOneUse())
6662 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6663 Subtract(RHS, BOp1C));
6664 } else if (RHSV == 0) {
6665 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6666 // efficiently invertible, or if the add has just this one use.
6667 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6668
6669 if (Value *NegVal = dyn_castNegVal(BOp1))
6670 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6671 else if (Value *NegVal = dyn_castNegVal(BOp0))
6672 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6673 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006674 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006675 InsertNewInstBefore(Neg, ICI);
6676 Neg->takeName(BO);
6677 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6678 }
6679 }
6680 break;
6681 case Instruction::Xor:
6682 // For the xor case, we can xor two constants together, eliminating
6683 // the explicit xor.
6684 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6685 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6686 ConstantExpr::getXor(RHS, BOC));
6687
6688 // FALLTHROUGH
6689 case Instruction::Sub:
6690 // Replace (([sub|xor] A, B) != 0) with (A != B)
6691 if (RHSV == 0)
6692 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6693 BO->getOperand(1));
6694 break;
6695
6696 case Instruction::Or:
6697 // If bits are being or'd in that are not present in the constant we
6698 // are comparing against, then the comparison could never succeed!
6699 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6700 Constant *NotCI = ConstantExpr::getNot(RHS);
6701 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6702 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6703 isICMP_NE));
6704 }
6705 break;
6706
6707 case Instruction::And:
6708 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6709 // If bits are being compared against that are and'd out, then the
6710 // comparison can never succeed!
6711 if ((RHSV & ~BOC->getValue()) != 0)
6712 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6713 isICMP_NE));
6714
6715 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6716 if (RHS == BOC && RHSV.isPowerOf2())
6717 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6718 ICmpInst::ICMP_NE, LHSI,
6719 Constant::getNullValue(RHS->getType()));
6720
6721 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6722 if (isSignBit(BOC)) {
6723 Value *X = BO->getOperand(0);
6724 Constant *Zero = Constant::getNullValue(X->getType());
6725 ICmpInst::Predicate pred = isICMP_NE ?
6726 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6727 return new ICmpInst(pred, X, Zero);
6728 }
6729
6730 // ((X & ~7) == 0) --> X < 8
6731 if (RHSV == 0 && isHighOnes(BOC)) {
6732 Value *X = BO->getOperand(0);
6733 Constant *NegX = ConstantExpr::getNeg(BOC);
6734 ICmpInst::Predicate pred = isICMP_NE ?
6735 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6736 return new ICmpInst(pred, X, NegX);
6737 }
6738 }
6739 default: break;
6740 }
6741 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6742 // Handle icmp {eq|ne} <intrinsic>, intcst.
6743 if (II->getIntrinsicID() == Intrinsic::bswap) {
6744 AddToWorkList(II);
6745 ICI.setOperand(0, II->getOperand(1));
6746 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6747 return &ICI;
6748 }
6749 }
6750 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006751 // If the LHS is a cast from an integral value of the same size,
6752 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006753 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6754 Value *CastOp = Cast->getOperand(0);
6755 const Type *SrcTy = CastOp->getType();
6756 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6757 if (SrcTy->isInteger() &&
6758 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6759 // If this is an unsigned comparison, try to make the comparison use
6760 // smaller constant values.
6761 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6762 // X u< 128 => X s> -1
6763 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6764 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6765 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6766 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6767 // X u> 127 => X s< 0
6768 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6769 Constant::getNullValue(SrcTy));
6770 }
6771 }
6772 }
6773 }
6774 return 0;
6775}
6776
6777/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6778/// We only handle extending casts so far.
6779///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006780Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6781 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006782 Value *LHSCIOp = LHSCI->getOperand(0);
6783 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006784 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006785 Value *RHSCIOp;
6786
Chris Lattner8c756c12007-05-05 22:41:33 +00006787 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6788 // integer type is the same size as the pointer type.
6789 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6790 getTargetData().getPointerSizeInBits() ==
6791 cast<IntegerType>(DestTy)->getBitWidth()) {
6792 Value *RHSOp = 0;
6793 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006794 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006795 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6796 RHSOp = RHSC->getOperand(0);
6797 // If the pointer types don't match, insert a bitcast.
6798 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006799 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006800 }
6801
6802 if (RHSOp)
6803 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6804 }
6805
6806 // The code below only handles extension cast instructions, so far.
6807 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006808 if (LHSCI->getOpcode() != Instruction::ZExt &&
6809 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006810 return 0;
6811
Reid Spencere4d87aa2006-12-23 06:05:41 +00006812 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6813 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006814
Reid Spencere4d87aa2006-12-23 06:05:41 +00006815 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006816 // Not an extension from the same type?
6817 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006818 if (RHSCIOp->getType() != LHSCIOp->getType())
6819 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006820
Nick Lewycky4189a532008-01-28 03:48:02 +00006821 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006822 // and the other is a zext), then we can't handle this.
6823 if (CI->getOpcode() != LHSCI->getOpcode())
6824 return 0;
6825
Nick Lewycky4189a532008-01-28 03:48:02 +00006826 // Deal with equality cases early.
6827 if (ICI.isEquality())
6828 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6829
6830 // A signed comparison of sign extended values simplifies into a
6831 // signed comparison.
6832 if (isSignedCmp && isSignedExt)
6833 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6834
6835 // The other three cases all fold into an unsigned comparison.
6836 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006837 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006838
Reid Spencere4d87aa2006-12-23 06:05:41 +00006839 // If we aren't dealing with a constant on the RHS, exit early
6840 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6841 if (!CI)
6842 return 0;
6843
6844 // Compute the constant that would happen if we truncated to SrcTy then
6845 // reextended to DestTy.
6846 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6847 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6848
6849 // If the re-extended constant didn't change...
6850 if (Res2 == CI) {
6851 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6852 // For example, we might have:
6853 // %A = sext short %X to uint
6854 // %B = icmp ugt uint %A, 1330
6855 // It is incorrect to transform this into
6856 // %B = icmp ugt short %X, 1330
6857 // because %A may have negative value.
6858 //
6859 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6860 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006861 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006862 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6863 else
6864 return 0;
6865 }
6866
6867 // The re-extended constant changed so the constant cannot be represented
6868 // in the shorter type. Consequently, we cannot emit a simple comparison.
6869
6870 // First, handle some easy cases. We know the result cannot be equal at this
6871 // point so handle the ICI.isEquality() cases
6872 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006873 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006874 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006875 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006876
6877 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6878 // should have been folded away previously and not enter in here.
6879 Value *Result;
6880 if (isSignedCmp) {
6881 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006882 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006883 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006884 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006885 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006886 } else {
6887 // We're performing an unsigned comparison.
6888 if (isSignedExt) {
6889 // We're performing an unsigned comp with a sign extended value.
6890 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006891 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006892 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6893 NegOne, ICI.getName()), ICI);
6894 } else {
6895 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006896 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006897 }
6898 }
6899
6900 // Finally, return the value computed.
6901 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6902 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6903 return ReplaceInstUsesWith(ICI, Result);
6904 } else {
6905 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6906 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6907 "ICmp should be folded!");
6908 if (Constant *CI = dyn_cast<Constant>(Result))
6909 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6910 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006911 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006912 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006913}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006914
Reid Spencer832254e2007-02-02 02:16:23 +00006915Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6916 return commonShiftTransforms(I);
6917}
6918
6919Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6920 return commonShiftTransforms(I);
6921}
6922
6923Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006924 if (Instruction *R = commonShiftTransforms(I))
6925 return R;
6926
6927 Value *Op0 = I.getOperand(0);
6928
6929 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6930 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6931 if (CSI->isAllOnesValue())
6932 return ReplaceInstUsesWith(I, CSI);
6933
6934 // See if we can turn a signed shr into an unsigned shr.
6935 if (MaskedValueIsZero(Op0,
6936 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006937 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006938
6939 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006940}
6941
6942Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6943 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006944 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006945
6946 // shl X, 0 == X and shr X, 0 == X
6947 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006948 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006949 Op0 == Constant::getNullValue(Op0->getType()))
6950 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006951
Reid Spencere4d87aa2006-12-23 06:05:41 +00006952 if (isa<UndefValue>(Op0)) {
6953 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006954 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006955 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006956 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6957 }
6958 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006959 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6960 return ReplaceInstUsesWith(I, Op0);
6961 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006962 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006963 }
6964
Chris Lattner2eefe512004-04-09 19:05:30 +00006965 // Try to fold constant and into select arguments.
6966 if (isa<Constant>(Op0))
6967 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006968 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006969 return R;
6970
Reid Spencerb83eb642006-10-20 07:07:24 +00006971 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006972 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6973 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006974 return 0;
6975}
6976
Reid Spencerb83eb642006-10-20 07:07:24 +00006977Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006978 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006979 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006980
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006981 // See if we can simplify any instructions used by the instruction whose sole
6982 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006983 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6984 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6985 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006986 KnownZero, KnownOne))
6987 return &I;
6988
Chris Lattner4d5542c2006-01-06 07:12:35 +00006989 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6990 // of a signed value.
6991 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006992 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006993 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006994 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6995 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006996 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006997 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006998 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006999 }
7000
7001 // ((X*C1) << C2) == (X * (C1 << C2))
7002 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7003 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7004 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007005 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007006 ConstantExpr::getShl(BOOp, Op1));
7007
7008 // Try to fold constant and into select arguments.
7009 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7010 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7011 return R;
7012 if (isa<PHINode>(Op0))
7013 if (Instruction *NV = FoldOpIntoPhi(I))
7014 return NV;
7015
Chris Lattner8999dd32007-12-22 09:07:47 +00007016 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7017 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7018 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7019 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7020 // place. Don't try to do this transformation in this case. Also, we
7021 // require that the input operand is a shift-by-constant so that we have
7022 // confidence that the shifts will get folded together. We could do this
7023 // xform in more cases, but it is unlikely to be profitable.
7024 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7025 isa<ConstantInt>(TrOp->getOperand(1))) {
7026 // Okay, we'll do this xform. Make the shift of shift.
7027 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007028 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007029 I.getName());
7030 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7031
7032 // For logical shifts, the truncation has the effect of making the high
7033 // part of the register be zeros. Emulate this by inserting an AND to
7034 // clear the top bits as needed. This 'and' will usually be zapped by
7035 // other xforms later if dead.
7036 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7037 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7038 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7039
7040 // The mask we constructed says what the trunc would do if occurring
7041 // between the shifts. We want to know the effect *after* the second
7042 // shift. We know that it is a logical shift by a constant, so adjust the
7043 // mask as appropriate.
7044 if (I.getOpcode() == Instruction::Shl)
7045 MaskV <<= Op1->getZExtValue();
7046 else {
7047 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7048 MaskV = MaskV.lshr(Op1->getZExtValue());
7049 }
7050
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007051 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007052 TI->getName());
7053 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7054
7055 // Return the value truncated to the interesting size.
7056 return new TruncInst(And, I.getType());
7057 }
7058 }
7059
Chris Lattner4d5542c2006-01-06 07:12:35 +00007060 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007061 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7062 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7063 Value *V1, *V2;
7064 ConstantInt *CC;
7065 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007066 default: break;
7067 case Instruction::Add:
7068 case Instruction::And:
7069 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007070 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007071 // These operators commute.
7072 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007073 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7074 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007075 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007076 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007077 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007078 Op0BO->getName());
7079 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007080 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007081 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007082 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007083 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007084 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007085 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007086 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007087 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007088
Chris Lattner150f12a2005-09-18 06:30:59 +00007089 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007090 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007091 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007092 match(Op0BOOp1,
7093 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00007094 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7095 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007096 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007097 Op0BO->getOperand(0), Op1,
7098 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007099 InsertNewInstBefore(YS, I); // (Y << C)
7100 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007101 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007102 V1->getName()+".mask");
7103 InsertNewInstBefore(XM, I); // X & (CC << C)
7104
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007105 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007106 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007107 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007108
Reid Spencera07cb7d2007-02-02 14:41:37 +00007109 // FALL THROUGH.
7110 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007111 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007112 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7113 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007114 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007115 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007116 Op0BO->getOperand(1), Op1,
7117 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007118 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007119 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007120 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007121 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007122 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007123 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007124 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007125 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007126 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007127
Chris Lattner13d4ab42006-05-31 21:14:00 +00007128 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007129 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7130 match(Op0BO->getOperand(0),
7131 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007132 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007133 cast<BinaryOperator>(Op0BO->getOperand(0))
7134 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007135 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007136 Op0BO->getOperand(1), Op1,
7137 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007138 InsertNewInstBefore(YS, I); // (Y << C)
7139 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007140 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007141 V1->getName()+".mask");
7142 InsertNewInstBefore(XM, I); // X & (CC << C)
7143
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007144 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007145 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007146
Chris Lattner11021cb2005-09-18 05:12:10 +00007147 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007148 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007149 }
7150
7151
7152 // If the operand is an bitwise operator with a constant RHS, and the
7153 // shift is the only use, we can pull it out of the shift.
7154 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7155 bool isValid = true; // Valid only for And, Or, Xor
7156 bool highBitSet = false; // Transform if high bit of constant set?
7157
7158 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007159 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007160 case Instruction::Add:
7161 isValid = isLeftShift;
7162 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007163 case Instruction::Or:
7164 case Instruction::Xor:
7165 highBitSet = false;
7166 break;
7167 case Instruction::And:
7168 highBitSet = true;
7169 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007170 }
7171
7172 // If this is a signed shift right, and the high bit is modified
7173 // by the logical operation, do not perform the transformation.
7174 // The highBitSet boolean indicates the value of the high bit of
7175 // the constant which would cause it to be modified for this
7176 // operation.
7177 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007178 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007179 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007180
7181 if (isValid) {
7182 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7183
7184 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007185 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007186 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007187 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007188
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007189 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007190 NewRHS);
7191 }
7192 }
7193 }
7194 }
7195
Chris Lattnerad0124c2006-01-06 07:52:12 +00007196 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007197 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7198 if (ShiftOp && !ShiftOp->isShift())
7199 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007200
Reid Spencerb83eb642006-10-20 07:07:24 +00007201 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007202 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007203 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7204 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007205 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7206 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7207 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007208
Zhou Sheng4351c642007-04-02 08:20:41 +00007209 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007210 if (AmtSum > TypeBits)
7211 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007212
7213 const IntegerType *Ty = cast<IntegerType>(I.getType());
7214
7215 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007216 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007217 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007218 ConstantInt::get(Ty, AmtSum));
7219 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7220 I.getOpcode() == Instruction::AShr) {
7221 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007222 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007223 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7224 I.getOpcode() == Instruction::LShr) {
7225 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7226 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007227 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007228 InsertNewInstBefore(Shift, I);
7229
Zhou Shenge9e03f62007-03-28 15:02:20 +00007230 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007231 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007232 }
7233
Chris Lattnerb87056f2007-02-05 00:57:54 +00007234 // Okay, if we get here, one shift must be left, and the other shift must be
7235 // right. See if the amounts are equal.
7236 if (ShiftAmt1 == ShiftAmt2) {
7237 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7238 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007239 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007240 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007241 }
7242 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7243 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007244 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007245 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007246 }
7247 // We can simplify ((X << C) >>s C) into a trunc + sext.
7248 // NOTE: we could do this for any C, but that would make 'unusual' integer
7249 // types. For now, just stick to ones well-supported by the code
7250 // generators.
7251 const Type *SExtType = 0;
7252 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007253 case 1 :
7254 case 8 :
7255 case 16 :
7256 case 32 :
7257 case 64 :
7258 case 128:
7259 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7260 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007261 default: break;
7262 }
7263 if (SExtType) {
7264 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7265 InsertNewInstBefore(NewTrunc, I);
7266 return new SExtInst(NewTrunc, Ty);
7267 }
7268 // Otherwise, we can't handle it yet.
7269 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007270 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007271
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007272 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007273 if (I.getOpcode() == Instruction::Shl) {
7274 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7275 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007276 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007277 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007278 InsertNewInstBefore(Shift, I);
7279
Reid Spencer55702aa2007-03-25 21:11:44 +00007280 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007281 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007282 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007283
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007284 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007285 if (I.getOpcode() == Instruction::LShr) {
7286 assert(ShiftOp->getOpcode() == Instruction::Shl);
7287 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007288 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007289 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007290
Reid Spencerd5e30f02007-03-26 17:18:58 +00007291 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007292 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007293 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007294
7295 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7296 } else {
7297 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007298 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007299
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007300 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007301 if (I.getOpcode() == Instruction::Shl) {
7302 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7303 ShiftOp->getOpcode() == Instruction::AShr);
7304 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007305 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007306 ConstantInt::get(Ty, ShiftDiff));
7307 InsertNewInstBefore(Shift, I);
7308
Reid Spencer55702aa2007-03-25 21:11:44 +00007309 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007310 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007311 }
7312
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007313 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007314 if (I.getOpcode() == Instruction::LShr) {
7315 assert(ShiftOp->getOpcode() == Instruction::Shl);
7316 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007317 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007318 InsertNewInstBefore(Shift, I);
7319
Reid Spencer68d27cf2007-03-26 23:45:51 +00007320 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007321 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007322 }
7323
7324 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007325 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007326 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007327 return 0;
7328}
7329
Chris Lattnera1be5662002-05-02 17:06:02 +00007330
Chris Lattnercfd65102005-10-29 04:36:15 +00007331/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7332/// expression. If so, decompose it, returning some value X, such that Val is
7333/// X*Scale+Offset.
7334///
7335static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007336 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007337 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007338 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007339 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007340 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007341 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007342 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7343 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7344 if (I->getOpcode() == Instruction::Shl) {
7345 // This is a value scaled by '1 << the shift amt'.
7346 Scale = 1U << RHS->getZExtValue();
7347 Offset = 0;
7348 return I->getOperand(0);
7349 } else if (I->getOpcode() == Instruction::Mul) {
7350 // This value is scaled by 'RHS'.
7351 Scale = RHS->getZExtValue();
7352 Offset = 0;
7353 return I->getOperand(0);
7354 } else if (I->getOpcode() == Instruction::Add) {
7355 // We have X+C. Check to see if we really have (X*C2)+C1,
7356 // where C1 is divisible by C2.
7357 unsigned SubScale;
7358 Value *SubVal =
7359 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7360 Offset += RHS->getZExtValue();
7361 Scale = SubScale;
7362 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007363 }
7364 }
7365 }
7366
7367 // Otherwise, we can't look past this.
7368 Scale = 1;
7369 Offset = 0;
7370 return Val;
7371}
7372
7373
Chris Lattnerb3f83972005-10-24 06:03:58 +00007374/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7375/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007376Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007377 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007378 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007379
Chris Lattnerb53c2382005-10-24 06:22:12 +00007380 // Remove any uses of AI that are dead.
7381 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007382
Chris Lattnerb53c2382005-10-24 06:22:12 +00007383 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7384 Instruction *User = cast<Instruction>(*UI++);
7385 if (isInstructionTriviallyDead(User)) {
7386 while (UI != E && *UI == User)
7387 ++UI; // If this instruction uses AI more than once, don't break UI.
7388
Chris Lattnerb53c2382005-10-24 06:22:12 +00007389 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007390 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007391 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007392 }
7393 }
7394
Chris Lattnerb3f83972005-10-24 06:03:58 +00007395 // Get the type really allocated and the type casted to.
7396 const Type *AllocElTy = AI.getAllocatedType();
7397 const Type *CastElTy = PTy->getElementType();
7398 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007399
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007400 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7401 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007402 if (CastElTyAlign < AllocElTyAlign) return 0;
7403
Chris Lattner39387a52005-10-24 06:35:18 +00007404 // If the allocation has multiple uses, only promote it if we are strictly
7405 // increasing the alignment of the resultant allocation. If we keep it the
7406 // same, we open the door to infinite loops of various kinds.
7407 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7408
Duncan Sands514ab342007-11-01 20:53:16 +00007409 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7410 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007411 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007412
Chris Lattner455fcc82005-10-29 03:19:53 +00007413 // See if we can satisfy the modulus by pulling a scale out of the array
7414 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007415 unsigned ArraySizeScale;
7416 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007417 Value *NumElements = // See if the array size is a decomposable linear expr.
7418 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7419
Chris Lattner455fcc82005-10-29 03:19:53 +00007420 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7421 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007422 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7423 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007424
Chris Lattner455fcc82005-10-29 03:19:53 +00007425 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7426 Value *Amt = 0;
7427 if (Scale == 1) {
7428 Amt = NumElements;
7429 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007430 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007431 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7432 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007433 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007434 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007435 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007436 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007437 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007438 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007439 }
7440
Jeff Cohen86796be2007-04-04 16:58:57 +00007441 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7442 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007443 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007444 Amt = InsertNewInstBefore(Tmp, AI);
7445 }
7446
Chris Lattnerb3f83972005-10-24 06:03:58 +00007447 AllocationInst *New;
7448 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007449 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007450 else
Chris Lattner6934a042007-02-11 01:23:03 +00007451 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007452 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007453 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007454
7455 // If the allocation has multiple uses, insert a cast and change all things
7456 // that used it to use the new cast. This will also hack on CI, but it will
7457 // die soon.
7458 if (!AI.hasOneUse()) {
7459 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007460 // New is the allocation instruction, pointer typed. AI is the original
7461 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7462 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007463 InsertNewInstBefore(NewCast, AI);
7464 AI.replaceAllUsesWith(NewCast);
7465 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007466 return ReplaceInstUsesWith(CI, New);
7467}
7468
Chris Lattner70074e02006-05-13 02:06:03 +00007469/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007470/// and return it as type Ty without inserting any new casts and without
7471/// changing the computed value. This is used by code that tries to decide
7472/// whether promoting or shrinking integer operations to wider or smaller types
7473/// will allow us to eliminate a truncate or extend.
7474///
7475/// This is a truncation operation if Ty is smaller than V->getType(), or an
7476/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007477bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7478 unsigned CastOpc,
7479 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007480 // We can always evaluate constants in another type.
7481 if (isa<ConstantInt>(V))
7482 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007483
7484 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007485 if (!I) return false;
7486
7487 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007488
Chris Lattner951626b2007-08-02 06:11:14 +00007489 // If this is an extension or truncate, we can often eliminate it.
7490 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7491 // If this is a cast from the destination type, we can trivially eliminate
7492 // it, and this will remove a cast overall.
7493 if (I->getOperand(0)->getType() == Ty) {
7494 // If the first operand is itself a cast, and is eliminable, do not count
7495 // this as an eliminable cast. We would prefer to eliminate those two
7496 // casts first.
7497 if (!isa<CastInst>(I->getOperand(0)))
7498 ++NumCastsRemoved;
7499 return true;
7500 }
7501 }
7502
7503 // We can't extend or shrink something that has multiple uses: doing so would
7504 // require duplicating the instruction in general, which isn't profitable.
7505 if (!I->hasOneUse()) return false;
7506
Chris Lattner70074e02006-05-13 02:06:03 +00007507 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007508 case Instruction::Add:
7509 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007510 case Instruction::And:
7511 case Instruction::Or:
7512 case Instruction::Xor:
7513 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007514 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7515 NumCastsRemoved) &&
7516 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7517 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007518
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007519 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007520 // A multiply can be truncated by truncating its operands.
7521 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7522 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7523 NumCastsRemoved) &&
7524 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7525 NumCastsRemoved);
7526
Chris Lattner46b96052006-11-29 07:18:39 +00007527 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007528 // If we are truncating the result of this SHL, and if it's a shift of a
7529 // constant amount, we can always perform a SHL in a smaller type.
7530 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007531 uint32_t BitWidth = Ty->getBitWidth();
7532 if (BitWidth < OrigTy->getBitWidth() &&
7533 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007534 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7535 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007536 }
7537 break;
7538 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007539 // If this is a truncate of a logical shr, we can truncate it to a smaller
7540 // lshr iff we know that the bits we would otherwise be shifting in are
7541 // already zeros.
7542 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007543 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7544 uint32_t BitWidth = Ty->getBitWidth();
7545 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007546 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007547 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7548 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007549 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7550 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007551 }
7552 }
Chris Lattner46b96052006-11-29 07:18:39 +00007553 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007554 case Instruction::ZExt:
7555 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007556 case Instruction::Trunc:
7557 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007558 // can safely replace it. Note that replacing it does not reduce the number
7559 // of casts in the input.
7560 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007561 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007562
Reid Spencer3da59db2006-11-27 01:05:10 +00007563 break;
7564 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007565 // TODO: Can handle more cases here.
7566 break;
7567 }
7568
7569 return false;
7570}
7571
7572/// EvaluateInDifferentType - Given an expression that
7573/// CanEvaluateInDifferentType returns true for, actually insert the code to
7574/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007575Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007576 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007577 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007578 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007579
7580 // Otherwise, it must be an instruction.
7581 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007582 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007583 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007584 case Instruction::Add:
7585 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007586 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007587 case Instruction::And:
7588 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007589 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007590 case Instruction::AShr:
7591 case Instruction::LShr:
7592 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007593 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007594 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007595 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007596 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007597 break;
7598 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007599 case Instruction::Trunc:
7600 case Instruction::ZExt:
7601 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007602 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007603 // just return the source. There's no need to insert it because it is not
7604 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007605 if (I->getOperand(0)->getType() == Ty)
7606 return I->getOperand(0);
7607
Chris Lattner951626b2007-08-02 06:11:14 +00007608 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007609 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007610 Ty, I->getName());
7611 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007612 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007613 // TODO: Can handle more cases here.
7614 assert(0 && "Unreachable!");
7615 break;
7616 }
7617
7618 return InsertNewInstBefore(Res, *I);
7619}
7620
Reid Spencer3da59db2006-11-27 01:05:10 +00007621/// @brief Implement the transforms common to all CastInst visitors.
7622Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007623 Value *Src = CI.getOperand(0);
7624
Dan Gohman23d9d272007-05-11 21:10:54 +00007625 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007626 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007627 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007628 if (Instruction::CastOps opc =
7629 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7630 // The first cast (CSrc) is eliminable so we need to fix up or replace
7631 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007632 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007633 }
7634 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007635
Reid Spencer3da59db2006-11-27 01:05:10 +00007636 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007637 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7638 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7639 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007640
7641 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007642 if (isa<PHINode>(Src))
7643 if (Instruction *NV = FoldOpIntoPhi(CI))
7644 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007645
Reid Spencer3da59db2006-11-27 01:05:10 +00007646 return 0;
7647}
7648
Chris Lattnerd3e28342007-04-27 17:44:50 +00007649/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7650Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7651 Value *Src = CI.getOperand(0);
7652
Chris Lattnerd3e28342007-04-27 17:44:50 +00007653 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007654 // If casting the result of a getelementptr instruction with no offset, turn
7655 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007656 if (GEP->hasAllZeroIndices()) {
7657 // Changing the cast operand is usually not a good idea but it is safe
7658 // here because the pointer operand is being replaced with another
7659 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007660 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007661 CI.setOperand(0, GEP->getOperand(0));
7662 return &CI;
7663 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007664
7665 // If the GEP has a single use, and the base pointer is a bitcast, and the
7666 // GEP computes a constant offset, see if we can convert these three
7667 // instructions into fewer. This typically happens with unions and other
7668 // non-type-safe code.
7669 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7670 if (GEP->hasAllConstantIndices()) {
7671 // We are guaranteed to get a constant from EmitGEPOffset.
7672 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7673 int64_t Offset = OffsetV->getSExtValue();
7674
7675 // Get the base pointer input of the bitcast, and the type it points to.
7676 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7677 const Type *GEPIdxTy =
7678 cast<PointerType>(OrigBase->getType())->getElementType();
7679 if (GEPIdxTy->isSized()) {
7680 SmallVector<Value*, 8> NewIndices;
7681
Chris Lattnerc42e2262007-05-05 01:59:31 +00007682 // Start with the index over the outer type. Note that the type size
7683 // might be zero (even if the offset isn't zero) if the indexed type
7684 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007685 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007686 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007687 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007688 FirstIdx = Offset/TySize;
7689 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007690
Chris Lattnerc42e2262007-05-05 01:59:31 +00007691 // Handle silly modulus not returning values values [0..TySize).
7692 if (Offset < 0) {
7693 --FirstIdx;
7694 Offset += TySize;
7695 assert(Offset >= 0);
7696 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007697 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007698 }
7699
7700 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007701
7702 // Index into the types. If we fail, set OrigBase to null.
7703 while (Offset) {
7704 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7705 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007706 if (Offset < (int64_t)SL->getSizeInBytes()) {
7707 unsigned Elt = SL->getElementContainingOffset(Offset);
7708 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007709
Chris Lattner6b6aef82007-05-15 00:16:00 +00007710 Offset -= SL->getElementOffset(Elt);
7711 GEPIdxTy = STy->getElementType(Elt);
7712 } else {
7713 // Otherwise, we can't index into this, bail out.
7714 Offset = 0;
7715 OrigBase = 0;
7716 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007717 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7718 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007719 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007720 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7721 Offset %= EltSize;
7722 } else {
7723 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7724 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007725 GEPIdxTy = STy->getElementType();
7726 } else {
7727 // Otherwise, we can't index into this, bail out.
7728 Offset = 0;
7729 OrigBase = 0;
7730 }
7731 }
7732 if (OrigBase) {
7733 // If we were able to index down into an element, create the GEP
7734 // and bitcast the result. This eliminates one bitcast, potentially
7735 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007736 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7737 NewIndices.begin(),
7738 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007739 InsertNewInstBefore(NGEP, CI);
7740 NGEP->takeName(GEP);
7741
Chris Lattner9bc14642007-04-28 00:57:34 +00007742 if (isa<BitCastInst>(CI))
7743 return new BitCastInst(NGEP, CI.getType());
7744 assert(isa<PtrToIntInst>(CI));
7745 return new PtrToIntInst(NGEP, CI.getType());
7746 }
7747 }
7748 }
7749 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007750 }
7751
7752 return commonCastTransforms(CI);
7753}
7754
7755
7756
Chris Lattnerc739cd62007-03-03 05:27:34 +00007757/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7758/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007759/// cases.
7760/// @brief Implement the transforms common to CastInst with integer operands
7761Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7762 if (Instruction *Result = commonCastTransforms(CI))
7763 return Result;
7764
7765 Value *Src = CI.getOperand(0);
7766 const Type *SrcTy = Src->getType();
7767 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007768 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7769 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007770
Reid Spencer3da59db2006-11-27 01:05:10 +00007771 // See if we can simplify any instructions used by the LHS whose sole
7772 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007773 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7774 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007775 KnownZero, KnownOne))
7776 return &CI;
7777
7778 // If the source isn't an instruction or has more than one use then we
7779 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007780 Instruction *SrcI = dyn_cast<Instruction>(Src);
7781 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007782 return 0;
7783
Chris Lattnerc739cd62007-03-03 05:27:34 +00007784 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007785 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007786 if (!isa<BitCastInst>(CI) &&
7787 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007788 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007789 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007790 // eliminates the cast, so it is always a win. If this is a zero-extension,
7791 // we need to do an AND to maintain the clear top-part of the computation,
7792 // so we require that the input have eliminated at least one cast. If this
7793 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007794 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007795 bool DoXForm;
7796 switch (CI.getOpcode()) {
7797 default:
7798 // All the others use floating point so we shouldn't actually
7799 // get here because of the check above.
7800 assert(0 && "Unknown cast type");
7801 case Instruction::Trunc:
7802 DoXForm = true;
7803 break;
7804 case Instruction::ZExt:
7805 DoXForm = NumCastsRemoved >= 1;
7806 break;
7807 case Instruction::SExt:
7808 DoXForm = NumCastsRemoved >= 2;
7809 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007810 }
7811
7812 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007813 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7814 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007815 assert(Res->getType() == DestTy);
7816 switch (CI.getOpcode()) {
7817 default: assert(0 && "Unknown cast type!");
7818 case Instruction::Trunc:
7819 case Instruction::BitCast:
7820 // Just replace this cast with the result.
7821 return ReplaceInstUsesWith(CI, Res);
7822 case Instruction::ZExt: {
7823 // We need to emit an AND to clear the high bits.
7824 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007825 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7826 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007827 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007828 }
7829 case Instruction::SExt:
7830 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007831 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007832 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7833 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007834 }
7835 }
7836 }
7837
7838 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7839 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7840
7841 switch (SrcI->getOpcode()) {
7842 case Instruction::Add:
7843 case Instruction::Mul:
7844 case Instruction::And:
7845 case Instruction::Or:
7846 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007847 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007848 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7849 // Don't insert two casts if they cannot be eliminated. We allow
7850 // two casts to be inserted if the sizes are the same. This could
7851 // only be converting signedness, which is a noop.
7852 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007853 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7854 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007855 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007856 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7857 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007858 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007859 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007860 }
7861 }
7862
7863 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7864 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7865 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007866 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007867 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007868 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007869 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007870 }
7871 break;
7872 case Instruction::SDiv:
7873 case Instruction::UDiv:
7874 case Instruction::SRem:
7875 case Instruction::URem:
7876 // If we are just changing the sign, rewrite.
7877 if (DestBitSize == SrcBitSize) {
7878 // Don't insert two casts if they cannot be eliminated. We allow
7879 // two casts to be inserted if the sizes are the same. This could
7880 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007881 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7882 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007883 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7884 Op0, DestTy, SrcI);
7885 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7886 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007887 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007888 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7889 }
7890 }
7891 break;
7892
7893 case Instruction::Shl:
7894 // Allow changing the sign of the source operand. Do not allow
7895 // changing the size of the shift, UNLESS the shift amount is a
7896 // constant. We must not change variable sized shifts to a smaller
7897 // size, because it is undefined to shift more bits out than exist
7898 // in the value.
7899 if (DestBitSize == SrcBitSize ||
7900 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007901 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7902 Instruction::BitCast : Instruction::Trunc);
7903 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007904 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007905 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007906 }
7907 break;
7908 case Instruction::AShr:
7909 // If this is a signed shr, and if all bits shifted in are about to be
7910 // truncated off, turn it into an unsigned shr to allow greater
7911 // simplifications.
7912 if (DestBitSize < SrcBitSize &&
7913 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007914 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007915 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7916 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007917 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007918 }
7919 }
7920 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007921 }
7922 return 0;
7923}
7924
Chris Lattner8a9f5712007-04-11 06:57:46 +00007925Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007926 if (Instruction *Result = commonIntCastTransforms(CI))
7927 return Result;
7928
7929 Value *Src = CI.getOperand(0);
7930 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007931 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7932 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007933
7934 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7935 switch (SrcI->getOpcode()) {
7936 default: break;
7937 case Instruction::LShr:
7938 // We can shrink lshr to something smaller if we know the bits shifted in
7939 // are already zeros.
7940 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007941 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007942
7943 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007944 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007945 Value* SrcIOp0 = SrcI->getOperand(0);
7946 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007947 if (ShAmt >= DestBitWidth) // All zeros.
7948 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7949
7950 // Okay, we can shrink this. Truncate the input, then return a new
7951 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007952 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7953 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7954 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007955 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007956 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007957 } else { // This is a variable shr.
7958
7959 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7960 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7961 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007962 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007963 Value *One = ConstantInt::get(SrcI->getType(), 1);
7964
Reid Spencer832254e2007-02-02 02:16:23 +00007965 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007966 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007967 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007968 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007969 SrcI->getOperand(0),
7970 "tmp"), CI);
7971 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007972 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007973 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007974 }
7975 break;
7976 }
7977 }
7978
7979 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007980}
7981
Evan Chengb98a10e2008-03-24 00:21:34 +00007982/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7983/// in order to eliminate the icmp.
7984Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7985 bool DoXform) {
7986 // If we are just checking for a icmp eq of a single bit and zext'ing it
7987 // to an integer, then shift the bit to the appropriate place and then
7988 // cast to integer to avoid the comparison.
7989 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7990 const APInt &Op1CV = Op1C->getValue();
7991
7992 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7993 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7994 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7995 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7996 if (!DoXform) return ICI;
7997
7998 Value *In = ICI->getOperand(0);
7999 Value *Sh = ConstantInt::get(In->getType(),
8000 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008001 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008002 In->getName()+".lobit"),
8003 CI);
8004 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008005 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008006 false/*ZExt*/, "tmp", &CI);
8007
8008 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8009 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008010 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008011 In->getName()+".not"),
8012 CI);
8013 }
8014
8015 return ReplaceInstUsesWith(CI, In);
8016 }
8017
8018
8019
8020 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8021 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8022 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8023 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8024 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8025 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8026 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8027 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8028 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8029 // This only works for EQ and NE
8030 ICI->isEquality()) {
8031 // If Op1C some other power of two, convert:
8032 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8033 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8034 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8035 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8036
8037 APInt KnownZeroMask(~KnownZero);
8038 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8039 if (!DoXform) return ICI;
8040
8041 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8042 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8043 // (X&4) == 2 --> false
8044 // (X&4) != 2 --> true
8045 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8046 Res = ConstantExpr::getZExt(Res, CI.getType());
8047 return ReplaceInstUsesWith(CI, Res);
8048 }
8049
8050 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8051 Value *In = ICI->getOperand(0);
8052 if (ShiftAmt) {
8053 // Perform a logical shr by shiftamt.
8054 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008055 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008056 ConstantInt::get(In->getType(), ShiftAmt),
8057 In->getName()+".lobit"), CI);
8058 }
8059
8060 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8061 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008062 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008063 InsertNewInstBefore(cast<Instruction>(In), CI);
8064 }
8065
8066 if (CI.getType() == In->getType())
8067 return ReplaceInstUsesWith(CI, In);
8068 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008069 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008070 }
8071 }
8072 }
8073
8074 return 0;
8075}
8076
Chris Lattner8a9f5712007-04-11 06:57:46 +00008077Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008078 // If one of the common conversion will work ..
8079 if (Instruction *Result = commonIntCastTransforms(CI))
8080 return Result;
8081
8082 Value *Src = CI.getOperand(0);
8083
8084 // If this is a cast of a cast
8085 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008086 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8087 // types and if the sizes are just right we can convert this into a logical
8088 // 'and' which will be much cheaper than the pair of casts.
8089 if (isa<TruncInst>(CSrc)) {
8090 // Get the sizes of the types involved
8091 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008092 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8093 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8094 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008095 // If we're actually extending zero bits and the trunc is a no-op
8096 if (MidSize < DstSize && SrcSize == DstSize) {
8097 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00008098 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00008099 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00008100 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008101 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00008102 // Unfortunately, if the type changed, we need to cast it back.
8103 if (And->getType() != CI.getType()) {
8104 And->setName(CSrc->getName()+".mask");
8105 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008106 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00008107 }
8108 return And;
8109 }
8110 }
8111 }
8112
Evan Chengb98a10e2008-03-24 00:21:34 +00008113 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8114 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008115
Evan Chengb98a10e2008-03-24 00:21:34 +00008116 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8117 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8118 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8119 // of the (zext icmp) will be transformed.
8120 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8121 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8122 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8123 (transformZExtICmp(LHS, CI, false) ||
8124 transformZExtICmp(RHS, CI, false))) {
8125 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8126 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008127 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008128 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008129 }
8130
Reid Spencer3da59db2006-11-27 01:05:10 +00008131 return 0;
8132}
8133
Chris Lattner8a9f5712007-04-11 06:57:46 +00008134Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008135 if (Instruction *I = commonIntCastTransforms(CI))
8136 return I;
8137
Chris Lattner8a9f5712007-04-11 06:57:46 +00008138 Value *Src = CI.getOperand(0);
8139
8140 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
8141 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
8142 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8143 // If we are just checking for a icmp eq of a single bit and zext'ing it
8144 // to an integer, then shift the bit to the appropriate place and then
8145 // cast to integer to avoid the comparison.
8146 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8147 const APInt &Op1CV = Op1C->getValue();
8148
8149 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8150 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8151 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8152 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8153 Value *In = ICI->getOperand(0);
8154 Value *Sh = ConstantInt::get(In->getType(),
8155 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008156 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00008157 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008158 CI);
8159 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008160 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008161 true/*SExt*/, "tmp", &CI);
8162
8163 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008164 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00008165 In->getName()+".not"), CI);
8166
8167 return ReplaceInstUsesWith(CI, In);
8168 }
8169 }
8170 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00008171
8172 // See if the value being truncated is already sign extended. If so, just
8173 // eliminate the trunc/sext pair.
8174 if (getOpcode(Src) == Instruction::Trunc) {
8175 Value *Op = cast<User>(Src)->getOperand(0);
8176 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8177 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8178 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8179 unsigned NumSignBits = ComputeNumSignBits(Op);
8180
8181 if (OpBits == DestBits) {
8182 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8183 // bits, it is already ready.
8184 if (NumSignBits > DestBits-MidBits)
8185 return ReplaceInstUsesWith(CI, Op);
8186 } else if (OpBits < DestBits) {
8187 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8188 // bits, just sext from i32.
8189 if (NumSignBits > OpBits-MidBits)
8190 return new SExtInst(Op, CI.getType(), "tmp");
8191 } else {
8192 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8193 // bits, just truncate to i32.
8194 if (NumSignBits > OpBits-MidBits)
8195 return new TruncInst(Op, CI.getType(), "tmp");
8196 }
8197 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00008198
Chris Lattnerba417832007-04-11 06:12:58 +00008199 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008200}
8201
Chris Lattnerb7530652008-01-27 05:29:54 +00008202/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8203/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008204static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008205 APFloat F = CFP->getValueAPF();
8206 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00008207 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008208 return 0;
8209}
8210
8211/// LookThroughFPExtensions - If this is an fp extension instruction, look
8212/// through it until we get the source value.
8213static Value *LookThroughFPExtensions(Value *V) {
8214 if (Instruction *I = dyn_cast<Instruction>(V))
8215 if (I->getOpcode() == Instruction::FPExt)
8216 return LookThroughFPExtensions(I->getOperand(0));
8217
8218 // If this value is a constant, return the constant in the smallest FP type
8219 // that can accurately represent it. This allows us to turn
8220 // (float)((double)X+2.0) into x+2.0f.
8221 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8222 if (CFP->getType() == Type::PPC_FP128Ty)
8223 return V; // No constant folding of this.
8224 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008225 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008226 return V;
8227 if (CFP->getType() == Type::DoubleTy)
8228 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008229 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008230 return V;
8231 // Don't try to shrink to various long double types.
8232 }
8233
8234 return V;
8235}
8236
8237Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8238 if (Instruction *I = commonCastTransforms(CI))
8239 return I;
8240
8241 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8242 // smaller than the destination type, we can eliminate the truncate by doing
8243 // the add as the smaller type. This applies to add/sub/mul/div as well as
8244 // many builtins (sqrt, etc).
8245 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8246 if (OpI && OpI->hasOneUse()) {
8247 switch (OpI->getOpcode()) {
8248 default: break;
8249 case Instruction::Add:
8250 case Instruction::Sub:
8251 case Instruction::Mul:
8252 case Instruction::FDiv:
8253 case Instruction::FRem:
8254 const Type *SrcTy = OpI->getType();
8255 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8256 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8257 if (LHSTrunc->getType() != SrcTy &&
8258 RHSTrunc->getType() != SrcTy) {
8259 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8260 // If the source types were both smaller than the destination type of
8261 // the cast, do this xform.
8262 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8263 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8264 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8265 CI.getType(), CI);
8266 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8267 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008268 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008269 }
8270 }
8271 break;
8272 }
8273 }
8274 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008275}
8276
8277Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8278 return commonCastTransforms(CI);
8279}
8280
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008281Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8282 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8283 // mantissa to accurately represent all values of X. For example, do not
8284 // do this with i64->float->i64.
8285 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8286 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8287 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00008288 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008289 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8290
8291 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008292}
8293
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008294Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8295 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8296 // mantissa to accurately represent all values of X. For example, do not
8297 // do this with i64->float->i64.
8298 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8299 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8300 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00008301 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008302 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8303
8304 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008305}
8306
8307Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8308 return commonCastTransforms(CI);
8309}
8310
8311Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8312 return commonCastTransforms(CI);
8313}
8314
8315Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008316 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008317}
8318
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008319Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8320 if (Instruction *I = commonCastTransforms(CI))
8321 return I;
8322
8323 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8324 if (!DestPointee->isSized()) return 0;
8325
8326 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8327 ConstantInt *Cst;
8328 Value *X;
8329 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8330 m_ConstantInt(Cst)))) {
8331 // If the source and destination operands have the same type, see if this
8332 // is a single-index GEP.
8333 if (X->getType() == CI.getType()) {
8334 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00008335 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008336
8337 // Convert the constant to intptr type.
8338 APInt Offset = Cst->getValue();
8339 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8340
8341 // If Offset is evenly divisible by Size, we can do this xform.
8342 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8343 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008344 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008345 }
8346 }
8347 // TODO: Could handle other cases, e.g. where add is indexing into field of
8348 // struct etc.
8349 } else if (CI.getOperand(0)->hasOneUse() &&
8350 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8351 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8352 // "inttoptr+GEP" instead of "add+intptr".
8353
8354 // Get the size of the pointee type.
8355 uint64_t Size = TD->getABITypeSize(DestPointee);
8356
8357 // Convert the constant to intptr type.
8358 APInt Offset = Cst->getValue();
8359 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8360
8361 // If Offset is evenly divisible by Size, we can do this xform.
8362 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8363 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8364
8365 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8366 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008367 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008368 }
8369 }
8370 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008371}
8372
Chris Lattnerd3e28342007-04-27 17:44:50 +00008373Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008374 // If the operands are integer typed then apply the integer transforms,
8375 // otherwise just apply the common ones.
8376 Value *Src = CI.getOperand(0);
8377 const Type *SrcTy = Src->getType();
8378 const Type *DestTy = CI.getType();
8379
Chris Lattner42a75512007-01-15 02:27:26 +00008380 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008381 if (Instruction *Result = commonIntCastTransforms(CI))
8382 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008383 } else if (isa<PointerType>(SrcTy)) {
8384 if (Instruction *I = commonPointerCastTransforms(CI))
8385 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008386 } else {
8387 if (Instruction *Result = commonCastTransforms(CI))
8388 return Result;
8389 }
8390
8391
8392 // Get rid of casts from one type to the same type. These are useless and can
8393 // be replaced by the operand.
8394 if (DestTy == Src->getType())
8395 return ReplaceInstUsesWith(CI, Src);
8396
Reid Spencer3da59db2006-11-27 01:05:10 +00008397 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008398 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8399 const Type *DstElTy = DstPTy->getElementType();
8400 const Type *SrcElTy = SrcPTy->getElementType();
8401
Nate Begeman83ad90a2008-03-31 00:22:16 +00008402 // If the address spaces don't match, don't eliminate the bitcast, which is
8403 // required for changing types.
8404 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8405 return 0;
8406
Chris Lattnerd3e28342007-04-27 17:44:50 +00008407 // If we are casting a malloc or alloca to a pointer to a type of the same
8408 // size, rewrite the allocation instruction to allocate the "right" type.
8409 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8410 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8411 return V;
8412
Chris Lattnerd717c182007-05-05 22:32:24 +00008413 // If the source and destination are pointers, and this cast is equivalent
8414 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008415 // This can enhance SROA and other transforms that want type-safe pointers.
8416 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8417 unsigned NumZeros = 0;
8418 while (SrcElTy != DstElTy &&
8419 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8420 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8421 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8422 ++NumZeros;
8423 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008424
Chris Lattnerd3e28342007-04-27 17:44:50 +00008425 // If we found a path from the src to dest, create the getelementptr now.
8426 if (SrcElTy == DstElTy) {
8427 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008428 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8429 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008430 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008431 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008432
Reid Spencer3da59db2006-11-27 01:05:10 +00008433 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8434 if (SVI->hasOneUse()) {
8435 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8436 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008437 if (isa<VectorType>(DestTy) &&
8438 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008439 SVI->getType()->getNumElements()) {
8440 CastInst *Tmp;
8441 // If either of the operands is a cast from CI.getType(), then
8442 // evaluating the shuffle in the casted destination's type will allow
8443 // us to eliminate at least one cast.
8444 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8445 Tmp->getOperand(0)->getType() == DestTy) ||
8446 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8447 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008448 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8449 SVI->getOperand(0), DestTy, &CI);
8450 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8451 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008452 // Return a new shuffle vector. Use the same element ID's, as we
8453 // know the vector types match #elts.
8454 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008455 }
8456 }
8457 }
8458 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008459 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008460}
8461
Chris Lattnere576b912004-04-09 23:46:01 +00008462/// GetSelectFoldableOperands - We want to turn code that looks like this:
8463/// %C = or %A, %B
8464/// %D = select %cond, %C, %A
8465/// into:
8466/// %C = select %cond, %B, 0
8467/// %D = or %A, %C
8468///
8469/// Assuming that the specified instruction is an operand to the select, return
8470/// a bitmask indicating which operands of this instruction are foldable if they
8471/// equal the other incoming value of the select.
8472///
8473static unsigned GetSelectFoldableOperands(Instruction *I) {
8474 switch (I->getOpcode()) {
8475 case Instruction::Add:
8476 case Instruction::Mul:
8477 case Instruction::And:
8478 case Instruction::Or:
8479 case Instruction::Xor:
8480 return 3; // Can fold through either operand.
8481 case Instruction::Sub: // Can only fold on the amount subtracted.
8482 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008483 case Instruction::LShr:
8484 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008485 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008486 default:
8487 return 0; // Cannot fold
8488 }
8489}
8490
8491/// GetSelectFoldableConstant - For the same transformation as the previous
8492/// function, return the identity constant that goes into the select.
8493static Constant *GetSelectFoldableConstant(Instruction *I) {
8494 switch (I->getOpcode()) {
8495 default: assert(0 && "This cannot happen!"); abort();
8496 case Instruction::Add:
8497 case Instruction::Sub:
8498 case Instruction::Or:
8499 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008500 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008501 case Instruction::LShr:
8502 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008503 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008504 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008505 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008506 case Instruction::Mul:
8507 return ConstantInt::get(I->getType(), 1);
8508 }
8509}
8510
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008511/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8512/// have the same opcode and only one use each. Try to simplify this.
8513Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8514 Instruction *FI) {
8515 if (TI->getNumOperands() == 1) {
8516 // If this is a non-volatile load or a cast from the same type,
8517 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008518 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008519 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8520 return 0;
8521 } else {
8522 return 0; // unknown unary op.
8523 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008524
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008525 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008526 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8527 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008528 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008529 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008530 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008531 }
8532
Reid Spencer832254e2007-02-02 02:16:23 +00008533 // Only handle binary operators here.
8534 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008535 return 0;
8536
8537 // Figure out if the operations have any operands in common.
8538 Value *MatchOp, *OtherOpT, *OtherOpF;
8539 bool MatchIsOpZero;
8540 if (TI->getOperand(0) == FI->getOperand(0)) {
8541 MatchOp = TI->getOperand(0);
8542 OtherOpT = TI->getOperand(1);
8543 OtherOpF = FI->getOperand(1);
8544 MatchIsOpZero = true;
8545 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8546 MatchOp = TI->getOperand(1);
8547 OtherOpT = TI->getOperand(0);
8548 OtherOpF = FI->getOperand(0);
8549 MatchIsOpZero = false;
8550 } else if (!TI->isCommutative()) {
8551 return 0;
8552 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8553 MatchOp = TI->getOperand(0);
8554 OtherOpT = TI->getOperand(1);
8555 OtherOpF = FI->getOperand(0);
8556 MatchIsOpZero = true;
8557 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8558 MatchOp = TI->getOperand(1);
8559 OtherOpT = TI->getOperand(0);
8560 OtherOpF = FI->getOperand(1);
8561 MatchIsOpZero = true;
8562 } else {
8563 return 0;
8564 }
8565
8566 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008567 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8568 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008569 InsertNewInstBefore(NewSI, SI);
8570
8571 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8572 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008573 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008574 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008575 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008576 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008577 assert(0 && "Shouldn't get here");
8578 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008579}
8580
Chris Lattner3d69f462004-03-12 05:52:32 +00008581Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008582 Value *CondVal = SI.getCondition();
8583 Value *TrueVal = SI.getTrueValue();
8584 Value *FalseVal = SI.getFalseValue();
8585
8586 // select true, X, Y -> X
8587 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008588 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008589 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008590
8591 // select C, X, X -> X
8592 if (TrueVal == FalseVal)
8593 return ReplaceInstUsesWith(SI, TrueVal);
8594
Chris Lattnere87597f2004-10-16 18:11:37 +00008595 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8596 return ReplaceInstUsesWith(SI, FalseVal);
8597 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8598 return ReplaceInstUsesWith(SI, TrueVal);
8599 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8600 if (isa<Constant>(TrueVal))
8601 return ReplaceInstUsesWith(SI, TrueVal);
8602 else
8603 return ReplaceInstUsesWith(SI, FalseVal);
8604 }
8605
Reid Spencer4fe16d62007-01-11 18:21:29 +00008606 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008607 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008608 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008609 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008610 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008611 } else {
8612 // Change: A = select B, false, C --> A = and !B, C
8613 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008614 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008615 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008616 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008617 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008618 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008619 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008620 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008621 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008622 } else {
8623 // Change: A = select B, C, true --> A = or !B, C
8624 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008625 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008626 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008627 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008628 }
8629 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008630
8631 // select a, b, a -> a&b
8632 // select a, a, b -> a|b
8633 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008634 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008635 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008636 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008637 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008638
Chris Lattner2eefe512004-04-09 19:05:30 +00008639 // Selecting between two integer constants?
8640 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8641 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008642 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008643 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008644 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008645 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008646 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008647 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008648 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008649 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008650 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008651 }
Chris Lattnerba417832007-04-11 06:12:58 +00008652
8653 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008654
Reid Spencere4d87aa2006-12-23 06:05:41 +00008655 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008656
Reid Spencere4d87aa2006-12-23 06:05:41 +00008657 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008658 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008659 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008660 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008661 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008662 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008663 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008664 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008665 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008666 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008667 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008668 InsertNewInstBefore(SRA, SI);
8669
Reid Spencer3da59db2006-11-27 01:05:10 +00008670 // Finally, convert to the type of the select RHS. We figure out
8671 // if this requires a SExt, Trunc or BitCast based on the sizes.
8672 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008673 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8674 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008675 if (SRASize < SISize)
8676 opc = Instruction::SExt;
8677 else if (SRASize > SISize)
8678 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008679 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008680 }
8681 }
8682
8683
8684 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008685 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008686 // non-constant value, eliminate this whole mess. This corresponds to
8687 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008688 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008689 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008690 cast<Constant>(IC->getOperand(1))->isNullValue())
8691 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8692 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008693 isa<ConstantInt>(ICA->getOperand(1)) &&
8694 (ICA->getOperand(1) == TrueValC ||
8695 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008696 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8697 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008698 // know whether we have a icmp_ne or icmp_eq and whether the
8699 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008700 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008701 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008702 Value *V = ICA;
8703 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008704 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008705 Instruction::Xor, V, ICA->getOperand(1)), SI);
8706 return ReplaceInstUsesWith(SI, V);
8707 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008708 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008709 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008710
8711 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008712 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8713 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008714 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008715 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8716 // This is not safe in general for floating point:
8717 // consider X== -0, Y== +0.
8718 // It becomes safe if either operand is a nonzero constant.
8719 ConstantFP *CFPt, *CFPf;
8720 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8721 !CFPt->getValueAPF().isZero()) ||
8722 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8723 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008724 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008725 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008726 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008727 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008728 return ReplaceInstUsesWith(SI, TrueVal);
8729 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8730
Reid Spencere4d87aa2006-12-23 06:05:41 +00008731 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008732 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008733 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8734 // This is not safe in general for floating point:
8735 // consider X== -0, Y== +0.
8736 // It becomes safe if either operand is a nonzero constant.
8737 ConstantFP *CFPt, *CFPf;
8738 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8739 !CFPt->getValueAPF().isZero()) ||
8740 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8741 !CFPf->getValueAPF().isZero()))
8742 return ReplaceInstUsesWith(SI, FalseVal);
8743 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008744 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008745 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8746 return ReplaceInstUsesWith(SI, TrueVal);
8747 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8748 }
8749 }
8750
8751 // See if we are selecting two values based on a comparison of the two values.
8752 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8753 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8754 // Transform (X == Y) ? X : Y -> Y
8755 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8756 return ReplaceInstUsesWith(SI, FalseVal);
8757 // Transform (X != Y) ? X : Y -> X
8758 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8759 return ReplaceInstUsesWith(SI, TrueVal);
8760 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8761
8762 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8763 // Transform (X == Y) ? Y : X -> X
8764 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8765 return ReplaceInstUsesWith(SI, FalseVal);
8766 // Transform (X != Y) ? Y : X -> Y
8767 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008768 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008769 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8770 }
8771 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008772
Chris Lattner87875da2005-01-13 22:52:24 +00008773 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8774 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8775 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008776 Instruction *AddOp = 0, *SubOp = 0;
8777
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008778 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8779 if (TI->getOpcode() == FI->getOpcode())
8780 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8781 return IV;
8782
8783 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8784 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008785 if (TI->getOpcode() == Instruction::Sub &&
8786 FI->getOpcode() == Instruction::Add) {
8787 AddOp = FI; SubOp = TI;
8788 } else if (FI->getOpcode() == Instruction::Sub &&
8789 TI->getOpcode() == Instruction::Add) {
8790 AddOp = TI; SubOp = FI;
8791 }
8792
8793 if (AddOp) {
8794 Value *OtherAddOp = 0;
8795 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8796 OtherAddOp = AddOp->getOperand(1);
8797 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8798 OtherAddOp = AddOp->getOperand(0);
8799 }
8800
8801 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008802 // So at this point we know we have (Y -> OtherAddOp):
8803 // select C, (add X, Y), (sub X, Z)
8804 Value *NegVal; // Compute -Z
8805 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8806 NegVal = ConstantExpr::getNeg(C);
8807 } else {
8808 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008809 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008810 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008811
8812 Value *NewTrueOp = OtherAddOp;
8813 Value *NewFalseOp = NegVal;
8814 if (AddOp != TI)
8815 std::swap(NewTrueOp, NewFalseOp);
8816 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008817 SelectInst::Create(CondVal, NewTrueOp,
8818 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008819
8820 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008821 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008822 }
8823 }
8824 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008825
Chris Lattnere576b912004-04-09 23:46:01 +00008826 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008827 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008828 // See the comment above GetSelectFoldableOperands for a description of the
8829 // transformation we are doing here.
8830 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8831 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8832 !isa<Constant>(FalseVal))
8833 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8834 unsigned OpToFold = 0;
8835 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8836 OpToFold = 1;
8837 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8838 OpToFold = 2;
8839 }
8840
8841 if (OpToFold) {
8842 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008843 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008844 SelectInst::Create(SI.getCondition(),
8845 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008846 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008847 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008848 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008849 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008850 else {
8851 assert(0 && "Unknown instruction!!");
8852 }
8853 }
8854 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008855
Chris Lattnere576b912004-04-09 23:46:01 +00008856 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8857 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8858 !isa<Constant>(TrueVal))
8859 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8860 unsigned OpToFold = 0;
8861 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8862 OpToFold = 1;
8863 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8864 OpToFold = 2;
8865 }
8866
8867 if (OpToFold) {
8868 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008869 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008870 SelectInst::Create(SI.getCondition(), C,
8871 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008872 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008873 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008874 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008875 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008876 else
Chris Lattnere576b912004-04-09 23:46:01 +00008877 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008878 }
8879 }
8880 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008881
8882 if (BinaryOperator::isNot(CondVal)) {
8883 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8884 SI.setOperand(1, FalseVal);
8885 SI.setOperand(2, TrueVal);
8886 return &SI;
8887 }
8888
Chris Lattner3d69f462004-03-12 05:52:32 +00008889 return 0;
8890}
8891
Dan Gohmaneee962e2008-04-10 18:43:06 +00008892/// EnforceKnownAlignment - If the specified pointer points to an object that
8893/// we control, modify the object's alignment to PrefAlign. This isn't
8894/// often possible though. If alignment is important, a more reliable approach
8895/// is to simply align all global variables and allocation instructions to
8896/// their preferred alignment from the beginning.
8897///
8898static unsigned EnforceKnownAlignment(Value *V,
8899 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008900
Dan Gohmaneee962e2008-04-10 18:43:06 +00008901 User *U = dyn_cast<User>(V);
8902 if (!U) return Align;
8903
8904 switch (getOpcode(U)) {
8905 default: break;
8906 case Instruction::BitCast:
8907 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8908 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008909 // If all indexes are zero, it is just the alignment of the base pointer.
8910 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008911 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8912 if (!isa<Constant>(U->getOperand(i)) ||
8913 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008914 AllZeroOperands = false;
8915 break;
8916 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008917
8918 if (AllZeroOperands) {
8919 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008920 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008921 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008922 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008923 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008924 }
8925
8926 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8927 // If there is a large requested alignment and we can, bump up the alignment
8928 // of the global.
8929 if (!GV->isDeclaration()) {
8930 GV->setAlignment(PrefAlign);
8931 Align = PrefAlign;
8932 }
8933 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8934 // If there is a requested alignment and if this is an alloca, round up. We
8935 // don't do this for malloc, because some systems can't respect the request.
8936 if (isa<AllocaInst>(AI)) {
8937 AI->setAlignment(PrefAlign);
8938 Align = PrefAlign;
8939 }
8940 }
8941
8942 return Align;
8943}
8944
8945/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8946/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8947/// and it is more than the alignment of the ultimate object, see if we can
8948/// increase the alignment of the ultimate object, making this check succeed.
8949unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8950 unsigned PrefAlign) {
8951 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8952 sizeof(PrefAlign) * CHAR_BIT;
8953 APInt Mask = APInt::getAllOnesValue(BitWidth);
8954 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8955 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8956 unsigned TrailZ = KnownZero.countTrailingOnes();
8957 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8958
8959 if (PrefAlign > Align)
8960 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8961
8962 // We don't need to make any adjustment.
8963 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008964}
8965
Chris Lattnerf497b022008-01-13 23:50:23 +00008966Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008967 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8968 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008969 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8970 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8971
8972 if (CopyAlign < MinAlign) {
8973 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8974 return MI;
8975 }
8976
8977 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8978 // load/store.
8979 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8980 if (MemOpLength == 0) return 0;
8981
Chris Lattner37ac6082008-01-14 00:28:35 +00008982 // Source and destination pointer types are always "i8*" for intrinsic. See
8983 // if the size is something we can handle with a single primitive load/store.
8984 // A single load+store correctly handles overlapping memory in the memmove
8985 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008986 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008987 if (Size == 0) return MI; // Delete this mem transfer.
8988
8989 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008990 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008991
Chris Lattner37ac6082008-01-14 00:28:35 +00008992 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008993 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008994
8995 // Memcpy forces the use of i8* for the source and destination. That means
8996 // that if you're using memcpy to move one double around, you'll get a cast
8997 // from double* to i8*. We'd much rather use a double load+store rather than
8998 // an i64 load+store, here because this improves the odds that the source or
8999 // dest address will be promotable. See if we can find a better type than the
9000 // integer datatype.
9001 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9002 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9003 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9004 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9005 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009006 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009007 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9008 if (STy->getNumElements() == 1)
9009 SrcETy = STy->getElementType(0);
9010 else
9011 break;
9012 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9013 if (ATy->getNumElements() == 1)
9014 SrcETy = ATy->getElementType();
9015 else
9016 break;
9017 } else
9018 break;
9019 }
9020
Dan Gohman8f8e2692008-05-23 01:52:21 +00009021 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009022 NewPtrTy = PointerType::getUnqual(SrcETy);
9023 }
9024 }
9025
9026
Chris Lattnerf497b022008-01-13 23:50:23 +00009027 // If the memcpy/memmove provides better alignment info than we can
9028 // infer, use it.
9029 SrcAlign = std::max(SrcAlign, CopyAlign);
9030 DstAlign = std::max(DstAlign, CopyAlign);
9031
9032 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9033 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009034 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9035 InsertNewInstBefore(L, *MI);
9036 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9037
9038 // Set the size of the copy to 0, it will be deleted on the next iteration.
9039 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9040 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009041}
Chris Lattner3d69f462004-03-12 05:52:32 +00009042
Chris Lattner69ea9d22008-04-30 06:39:11 +00009043Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9044 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9045 if (MI->getAlignment()->getZExtValue() < Alignment) {
9046 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9047 return MI;
9048 }
9049
9050 // Extract the length and alignment and fill if they are constant.
9051 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9052 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9053 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9054 return 0;
9055 uint64_t Len = LenC->getZExtValue();
9056 Alignment = MI->getAlignment()->getZExtValue();
9057
9058 // If the length is zero, this is a no-op
9059 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9060
9061 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9062 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9063 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9064
9065 Value *Dest = MI->getDest();
9066 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9067
9068 // Alignment 0 is identity for alignment 1 for memset, but not store.
9069 if (Alignment == 0) Alignment = 1;
9070
9071 // Extract the fill value and store.
9072 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9073 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9074 Alignment), *MI);
9075
9076 // Set the size of the copy to 0, it will be deleted on the next iteration.
9077 MI->setLength(Constant::getNullValue(LenC->getType()));
9078 return MI;
9079 }
9080
9081 return 0;
9082}
9083
9084
Chris Lattner8b0ea312006-01-13 20:11:04 +00009085/// visitCallInst - CallInst simplification. This mostly only handles folding
9086/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9087/// the heavy lifting.
9088///
Chris Lattner9fe38862003-06-19 17:00:31 +00009089Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009090 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9091 if (!II) return visitCallSite(&CI);
9092
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009093 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9094 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009095 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009096 bool Changed = false;
9097
9098 // memmove/cpy/set of zero bytes is a noop.
9099 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9100 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9101
Chris Lattner35b9e482004-10-12 04:52:52 +00009102 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009103 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009104 // Replace the instruction with just byte operations. We would
9105 // transform other cases to loads/stores, but we don't know if
9106 // alignment is sufficient.
9107 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009108 }
9109
Chris Lattner35b9e482004-10-12 04:52:52 +00009110 // If we have a memmove and the source operation is a constant global,
9111 // then the source and dest pointers can't alias, so we can change this
9112 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009113 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009114 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9115 if (GVSrc->isConstant()) {
9116 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00009117 Intrinsic::ID MemCpyID;
9118 if (CI.getOperand(3)->getType() == Type::Int32Ty)
9119 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00009120 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00009121 MemCpyID = Intrinsic::memcpy_i64;
9122 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00009123 Changed = true;
9124 }
Chris Lattner95a959d2006-03-06 20:18:44 +00009125 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009126
Chris Lattner95a959d2006-03-06 20:18:44 +00009127 // If we can determine a pointer alignment that is bigger than currently
9128 // set, update the alignment.
9129 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009130 if (Instruction *I = SimplifyMemTransfer(MI))
9131 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009132 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9133 if (Instruction *I = SimplifyMemSet(MSI))
9134 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009135 }
9136
Chris Lattner8b0ea312006-01-13 20:11:04 +00009137 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009138 } else {
9139 switch (II->getIntrinsicID()) {
9140 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00009141 case Intrinsic::ppc_altivec_lvx:
9142 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009143 case Intrinsic::x86_sse_loadu_ps:
9144 case Intrinsic::x86_sse2_loadu_pd:
9145 case Intrinsic::x86_sse2_loadu_dq:
9146 // Turn PPC lvx -> load if the pointer is known aligned.
9147 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009148 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00009149 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9150 PointerType::getUnqual(II->getType()),
9151 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009152 return new LoadInst(Ptr);
9153 }
9154 break;
9155 case Intrinsic::ppc_altivec_stvx:
9156 case Intrinsic::ppc_altivec_stvxl:
9157 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009158 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009159 const Type *OpPtrTy =
9160 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009161 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009162 return new StoreInst(II->getOperand(1), Ptr);
9163 }
9164 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009165 case Intrinsic::x86_sse_storeu_ps:
9166 case Intrinsic::x86_sse2_storeu_pd:
9167 case Intrinsic::x86_sse2_storeu_dq:
9168 case Intrinsic::x86_sse2_storel_dq:
9169 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009170 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009171 const Type *OpPtrTy =
9172 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009173 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009174 return new StoreInst(II->getOperand(2), Ptr);
9175 }
9176 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00009177
9178 case Intrinsic::x86_sse_cvttss2si: {
9179 // These intrinsics only demands the 0th element of its input vector. If
9180 // we can simplify the input based on that, do so now.
9181 uint64_t UndefElts;
9182 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9183 UndefElts)) {
9184 II->setOperand(1, V);
9185 return II;
9186 }
9187 break;
9188 }
9189
Chris Lattnere2ed0572006-04-06 19:19:17 +00009190 case Intrinsic::ppc_altivec_vperm:
9191 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009192 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00009193 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9194
9195 // Check that all of the elements are integer constants or undefs.
9196 bool AllEltsOk = true;
9197 for (unsigned i = 0; i != 16; ++i) {
9198 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9199 !isa<UndefValue>(Mask->getOperand(i))) {
9200 AllEltsOk = false;
9201 break;
9202 }
9203 }
9204
9205 if (AllEltsOk) {
9206 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00009207 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9208 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009209 Value *Result = UndefValue::get(Op0->getType());
9210
9211 // Only extract each element once.
9212 Value *ExtractedElts[32];
9213 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9214
9215 for (unsigned i = 0; i != 16; ++i) {
9216 if (isa<UndefValue>(Mask->getOperand(i)))
9217 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00009218 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00009219 Idx &= 31; // Match the hardware behavior.
9220
9221 if (ExtractedElts[Idx] == 0) {
9222 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00009223 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009224 InsertNewInstBefore(Elt, CI);
9225 ExtractedElts[Idx] = Elt;
9226 }
9227
9228 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009229 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9230 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009231 InsertNewInstBefore(cast<Instruction>(Result), CI);
9232 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009233 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009234 }
9235 }
9236 break;
9237
Chris Lattnera728ddc2006-01-13 21:28:09 +00009238 case Intrinsic::stackrestore: {
9239 // If the save is right next to the restore, remove the restore. This can
9240 // happen when variable allocas are DCE'd.
9241 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9242 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9243 BasicBlock::iterator BI = SS;
9244 if (&*++BI == II)
9245 return EraseInstFromFunction(CI);
9246 }
9247 }
9248
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009249 // Scan down this block to see if there is another stack restore in the
9250 // same block without an intervening call/alloca.
9251 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009252 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009253 bool CannotRemove = false;
9254 for (++BI; &*BI != TI; ++BI) {
9255 if (isa<AllocaInst>(BI)) {
9256 CannotRemove = true;
9257 break;
9258 }
9259 if (isa<CallInst>(BI)) {
9260 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00009261 CannotRemove = true;
9262 break;
9263 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009264 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00009265 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009266 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009267 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009268
9269 // If the stack restore is in a return/unwind block and if there are no
9270 // allocas or calls between the restore and the return, nuke the restore.
9271 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9272 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009273 break;
9274 }
9275 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009276 }
9277
Chris Lattner8b0ea312006-01-13 20:11:04 +00009278 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009279}
9280
9281// InvokeInst simplification
9282//
9283Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009284 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009285}
9286
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009287/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9288/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009289static bool isSafeToEliminateVarargsCast(const CallSite CS,
9290 const CastInst * const CI,
9291 const TargetData * const TD,
9292 const int ix) {
9293 if (!CI->isLosslessCast())
9294 return false;
9295
9296 // The size of ByVal arguments is derived from the type, so we
9297 // can't change to a type with a different size. If the size were
9298 // passed explicitly we could avoid this check.
9299 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9300 return true;
9301
9302 const Type* SrcTy =
9303 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9304 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9305 if (!SrcTy->isSized() || !DstTy->isSized())
9306 return false;
9307 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9308 return false;
9309 return true;
9310}
9311
Chris Lattnera44d8a22003-10-07 22:32:43 +00009312// visitCallSite - Improvements for call and invoke instructions.
9313//
9314Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009315 bool Changed = false;
9316
9317 // If the callee is a constexpr cast of a function, attempt to move the cast
9318 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009319 if (transformConstExprCastCall(CS)) return 0;
9320
Chris Lattner6c266db2003-10-07 22:54:13 +00009321 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009322
Chris Lattner08b22ec2005-05-13 07:09:09 +00009323 if (Function *CalleeF = dyn_cast<Function>(Callee))
9324 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9325 Instruction *OldCall = CS.getInstruction();
9326 // If the call and callee calling conventions don't match, this call must
9327 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009328 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009329 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9330 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009331 if (!OldCall->use_empty())
9332 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9333 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9334 return EraseInstFromFunction(*OldCall);
9335 return 0;
9336 }
9337
Chris Lattner17be6352004-10-18 02:59:09 +00009338 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9339 // This instruction is not reachable, just remove it. We insert a store to
9340 // undef so that we know that this code is not reachable, despite the fact
9341 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009342 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009343 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009344 CS.getInstruction());
9345
9346 if (!CS.getInstruction()->use_empty())
9347 CS.getInstruction()->
9348 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9349
9350 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9351 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009352 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9353 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009354 }
Chris Lattner17be6352004-10-18 02:59:09 +00009355 return EraseInstFromFunction(*CS.getInstruction());
9356 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009357
Duncan Sandscdb6d922007-09-17 10:26:40 +00009358 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9359 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9360 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9361 return transformCallThroughTrampoline(CS);
9362
Chris Lattner6c266db2003-10-07 22:54:13 +00009363 const PointerType *PTy = cast<PointerType>(Callee->getType());
9364 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9365 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009366 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009367 // See if we can optimize any arguments passed through the varargs area of
9368 // the call.
9369 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009370 E = CS.arg_end(); I != E; ++I, ++ix) {
9371 CastInst *CI = dyn_cast<CastInst>(*I);
9372 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9373 *I = CI->getOperand(0);
9374 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009375 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009376 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009377 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009378
Duncan Sandsf0c33542007-12-19 21:13:37 +00009379 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009380 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009381 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009382 Changed = true;
9383 }
9384
Chris Lattner6c266db2003-10-07 22:54:13 +00009385 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009386}
9387
Chris Lattner9fe38862003-06-19 17:00:31 +00009388// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9389// attempt to move the cast to the arguments of the call/invoke.
9390//
9391bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9392 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9393 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009394 if (CE->getOpcode() != Instruction::BitCast ||
9395 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009396 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009397 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009398 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00009399 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00009400
9401 // Okay, this is a cast from a function to a different type. Unless doing so
9402 // would cause a type conversion of one of our arguments, change this call to
9403 // be a direct call with arguments casted to the appropriate types.
9404 //
9405 const FunctionType *FT = Callee->getFunctionType();
9406 const Type *OldRetTy = Caller->getType();
9407
Devang Patel75e6f022008-03-11 18:04:06 +00009408 if (isa<StructType>(FT->getReturnType()))
9409 return false; // TODO: Handle multiple return values.
9410
Chris Lattnerf78616b2004-01-14 06:06:08 +00009411 // Check to see if we are changing the return type...
9412 if (OldRetTy != FT->getReturnType()) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009413 if (Callee->isDeclaration() &&
Chris Lattner46013f42007-01-06 19:53:32 +00009414 // Conversion is ok if changing from pointer to int of same size.
9415 !(isa<PointerType>(FT->getReturnType()) &&
9416 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00009417 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009418
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009419 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009420 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00009421 FT->getReturnType() != Type::VoidTy &&
9422 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009423 return false; // Cannot transform this return value.
9424
Chris Lattner58d74912008-03-12 17:45:29 +00009425 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9426 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00009427 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9428 return false; // Attribute not compatible with transformed value.
9429 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009430
Chris Lattnerf78616b2004-01-14 06:06:08 +00009431 // If the callsite is an invoke instruction, and the return value is used by
9432 // a PHI node in a successor, we cannot change the return type of the call
9433 // because there is no place to put the cast instruction (without breaking
9434 // the critical edge). Bail out in this case.
9435 if (!Caller->use_empty())
9436 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9437 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9438 UI != E; ++UI)
9439 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9440 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009441 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009442 return false;
9443 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009444
9445 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9446 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009447
Chris Lattner9fe38862003-06-19 17:00:31 +00009448 CallSite::arg_iterator AI = CS.arg_begin();
9449 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9450 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009451 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009452
9453 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009454 return false; // Cannot transform this parameter value.
9455
Chris Lattner58d74912008-03-12 17:45:29 +00009456 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9457 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009458
Reid Spencer3da59db2006-11-27 01:05:10 +00009459 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009460 // Some conversions are safe even if we do not have a body.
9461 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00009462 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00009463 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00009464 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009465 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9466 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00009467 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00009468 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009469 }
9470
9471 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009472 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009473 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009474
Chris Lattner58d74912008-03-12 17:45:29 +00009475 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9476 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009477 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009478 // won't be dropping them. Check that these extra arguments have attributes
9479 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009480 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9481 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009482 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009483 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009484 if (PAttrs & ParamAttr::VarArgsIncompatible)
9485 return false;
9486 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009487
Chris Lattner9fe38862003-06-19 17:00:31 +00009488 // Okay, we decided that this is a safe thing to do: go ahead and start
9489 // inserting cast instructions as necessary...
9490 std::vector<Value*> Args;
9491 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009492 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009493 attrVec.reserve(NumCommonArgs);
9494
9495 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009496 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009497
9498 // If the return value is not being used, the type may not be compatible
9499 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009500 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009501
9502 // Add the new return attributes.
9503 if (RAttrs)
9504 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009505
9506 AI = CS.arg_begin();
9507 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9508 const Type *ParamTy = FT->getParamType(i);
9509 if ((*AI)->getType() == ParamTy) {
9510 Args.push_back(*AI);
9511 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009512 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009513 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009514 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009515 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009516 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009517
9518 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009519 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009520 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009521 }
9522
9523 // If the function takes more arguments than the call was taking, add them
9524 // now...
9525 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9526 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9527
9528 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009529 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009530 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009531 cerr << "WARNING: While resolving call to function '"
9532 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009533 } else {
9534 // Add all of the arguments in their promoted form to the arg list...
9535 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9536 const Type *PTy = getPromotedType((*AI)->getType());
9537 if (PTy != (*AI)->getType()) {
9538 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009539 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9540 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009541 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009542 InsertNewInstBefore(Cast, *Caller);
9543 Args.push_back(Cast);
9544 } else {
9545 Args.push_back(*AI);
9546 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009547
Duncan Sandse1e520f2008-01-13 08:02:44 +00009548 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009549 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009550 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9551 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009552 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009553 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009554
9555 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009556 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009557
Chris Lattner58d74912008-03-12 17:45:29 +00009558 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009559
Chris Lattner9fe38862003-06-19 17:00:31 +00009560 Instruction *NC;
9561 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009562 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009563 Args.begin(), Args.end(),
9564 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009565 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009566 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009567 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009568 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9569 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009570 CallInst *CI = cast<CallInst>(Caller);
9571 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009572 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009573 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009574 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009575 }
9576
Chris Lattner6934a042007-02-11 01:23:03 +00009577 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009578 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009579 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009580 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009581 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009582 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009583 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009584
9585 // If this is an invoke instruction, we should insert it after the first
9586 // non-phi, instruction in the normal successor block.
9587 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9588 BasicBlock::iterator I = II->getNormalDest()->begin();
9589 while (isa<PHINode>(I)) ++I;
9590 InsertNewInstBefore(NC, *I);
9591 } else {
9592 // Otherwise, it's a call, just insert cast right after the call instr
9593 InsertNewInstBefore(NC, *Caller);
9594 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009595 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009596 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009597 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009598 }
9599 }
9600
9601 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9602 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009603 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009604 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009605 return true;
9606}
9607
Duncan Sandscdb6d922007-09-17 10:26:40 +00009608// transformCallThroughTrampoline - Turn a call to a function created by the
9609// init_trampoline intrinsic into a direct call to the underlying function.
9610//
9611Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9612 Value *Callee = CS.getCalledValue();
9613 const PointerType *PTy = cast<PointerType>(Callee->getType());
9614 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009615 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009616
9617 // If the call already has the 'nest' attribute somewhere then give up -
9618 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009619 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009620 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009621
9622 IntrinsicInst *Tramp =
9623 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9624
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009625 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009626 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9627 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9628
Chris Lattner58d74912008-03-12 17:45:29 +00009629 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9630 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009631 unsigned NestIdx = 1;
9632 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009633 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009634
9635 // Look for a parameter marked with the 'nest' attribute.
9636 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9637 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009638 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009639 // Record the parameter type and any other attributes.
9640 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009641 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009642 break;
9643 }
9644
9645 if (NestTy) {
9646 Instruction *Caller = CS.getInstruction();
9647 std::vector<Value*> NewArgs;
9648 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9649
Chris Lattner58d74912008-03-12 17:45:29 +00009650 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9651 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009652
Duncan Sandscdb6d922007-09-17 10:26:40 +00009653 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009654 // mean appending it. Likewise for attributes.
9655
9656 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009657 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9658 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009659
Duncan Sandscdb6d922007-09-17 10:26:40 +00009660 {
9661 unsigned Idx = 1;
9662 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9663 do {
9664 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009665 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009666 Value *NestVal = Tramp->getOperand(3);
9667 if (NestVal->getType() != NestTy)
9668 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9669 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009670 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009671 }
9672
9673 if (I == E)
9674 break;
9675
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009676 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009677 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009678 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009679 NewAttrs.push_back
9680 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009681
9682 ++Idx, ++I;
9683 } while (1);
9684 }
9685
9686 // The trampoline may have been bitcast to a bogus type (FTy).
9687 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009688 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009689
Duncan Sandscdb6d922007-09-17 10:26:40 +00009690 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009691 NewTypes.reserve(FTy->getNumParams()+1);
9692
Duncan Sandscdb6d922007-09-17 10:26:40 +00009693 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009694 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009695 {
9696 unsigned Idx = 1;
9697 FunctionType::param_iterator I = FTy->param_begin(),
9698 E = FTy->param_end();
9699
9700 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009701 if (Idx == NestIdx)
9702 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009703 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009704
9705 if (I == E)
9706 break;
9707
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009708 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009709 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009710
9711 ++Idx, ++I;
9712 } while (1);
9713 }
9714
9715 // Replace the trampoline call with a direct call. Let the generic
9716 // code sort out any function type mismatches.
9717 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009718 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009719 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9720 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009721 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009722
9723 Instruction *NewCaller;
9724 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009725 NewCaller = InvokeInst::Create(NewCallee,
9726 II->getNormalDest(), II->getUnwindDest(),
9727 NewArgs.begin(), NewArgs.end(),
9728 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009729 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009730 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009731 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009732 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9733 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009734 if (cast<CallInst>(Caller)->isTailCall())
9735 cast<CallInst>(NewCaller)->setTailCall();
9736 cast<CallInst>(NewCaller)->
9737 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009738 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009739 }
9740 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9741 Caller->replaceAllUsesWith(NewCaller);
9742 Caller->eraseFromParent();
9743 RemoveFromWorkList(Caller);
9744 return 0;
9745 }
9746 }
9747
9748 // Replace the trampoline call with a direct call. Since there is no 'nest'
9749 // parameter, there is no need to adjust the argument list. Let the generic
9750 // code sort out any function type mismatches.
9751 Constant *NewCallee =
9752 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9753 CS.setCalledFunction(NewCallee);
9754 return CS.getInstruction();
9755}
9756
Chris Lattner7da52b22006-11-01 04:51:18 +00009757/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9758/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9759/// and a single binop.
9760Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9761 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009762 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9763 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009764 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009765 Value *LHSVal = FirstInst->getOperand(0);
9766 Value *RHSVal = FirstInst->getOperand(1);
9767
9768 const Type *LHSType = LHSVal->getType();
9769 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009770
9771 // Scan to see if all operands are the same opcode, all have one use, and all
9772 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009773 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009774 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009775 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009776 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009777 // types or GEP's with different index types.
9778 I->getOperand(0)->getType() != LHSType ||
9779 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009780 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009781
9782 // If they are CmpInst instructions, check their predicates
9783 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9784 if (cast<CmpInst>(I)->getPredicate() !=
9785 cast<CmpInst>(FirstInst)->getPredicate())
9786 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009787
9788 // Keep track of which operand needs a phi node.
9789 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9790 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009791 }
9792
Chris Lattner53738a42006-11-08 19:42:28 +00009793 // Otherwise, this is safe to transform, determine if it is profitable.
9794
9795 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9796 // Indexes are often folded into load/store instructions, so we don't want to
9797 // hide them behind a phi.
9798 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9799 return 0;
9800
Chris Lattner7da52b22006-11-01 04:51:18 +00009801 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009802 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009803 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009804 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009805 NewLHS = PHINode::Create(LHSType,
9806 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009807 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9808 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009809 InsertNewInstBefore(NewLHS, PN);
9810 LHSVal = NewLHS;
9811 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009812
9813 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009814 NewRHS = PHINode::Create(RHSType,
9815 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009816 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9817 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009818 InsertNewInstBefore(NewRHS, PN);
9819 RHSVal = NewRHS;
9820 }
9821
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009822 // Add all operands to the new PHIs.
9823 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9824 if (NewLHS) {
9825 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9826 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9827 }
9828 if (NewRHS) {
9829 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9830 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9831 }
9832 }
9833
Chris Lattner7da52b22006-11-01 04:51:18 +00009834 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009835 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009836 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009837 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009838 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009839 else {
9840 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009841 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009842 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009843}
9844
Chris Lattner76c73142006-11-01 07:13:54 +00009845/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9846/// of the block that defines it. This means that it must be obvious the value
9847/// of the load is not changed from the point of the load to the end of the
9848/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009849///
9850/// Finally, it is safe, but not profitable, to sink a load targetting a
9851/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9852/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009853static bool isSafeToSinkLoad(LoadInst *L) {
9854 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9855
9856 for (++BBI; BBI != E; ++BBI)
9857 if (BBI->mayWriteToMemory())
9858 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009859
9860 // Check for non-address taken alloca. If not address-taken already, it isn't
9861 // profitable to do this xform.
9862 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9863 bool isAddressTaken = false;
9864 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9865 UI != E; ++UI) {
9866 if (isa<LoadInst>(UI)) continue;
9867 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9868 // If storing TO the alloca, then the address isn't taken.
9869 if (SI->getOperand(1) == AI) continue;
9870 }
9871 isAddressTaken = true;
9872 break;
9873 }
9874
9875 if (!isAddressTaken)
9876 return false;
9877 }
9878
Chris Lattner76c73142006-11-01 07:13:54 +00009879 return true;
9880}
9881
Chris Lattner9fe38862003-06-19 17:00:31 +00009882
Chris Lattnerbac32862004-11-14 19:13:23 +00009883// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9884// operator and they all are only used by the PHI, PHI together their
9885// inputs, and do the operation once, to the result of the PHI.
9886Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9887 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9888
9889 // Scan the instruction, looking for input operations that can be folded away.
9890 // If all input operands to the phi are the same instruction (e.g. a cast from
9891 // the same type or "+42") we can pull the operation through the PHI, reducing
9892 // code size and simplifying code.
9893 Constant *ConstantOp = 0;
9894 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009895 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009896 if (isa<CastInst>(FirstInst)) {
9897 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009898 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009899 // Can fold binop, compare or shift here if the RHS is a constant,
9900 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009901 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009902 if (ConstantOp == 0)
9903 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009904 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9905 isVolatile = LI->isVolatile();
9906 // We can't sink the load if the loaded value could be modified between the
9907 // load and the PHI.
9908 if (LI->getParent() != PN.getIncomingBlock(0) ||
9909 !isSafeToSinkLoad(LI))
9910 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009911 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009912 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009913 return FoldPHIArgBinOpIntoPHI(PN);
9914 // Can't handle general GEPs yet.
9915 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009916 } else {
9917 return 0; // Cannot fold this operation.
9918 }
9919
9920 // Check to see if all arguments are the same operation.
9921 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9922 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9923 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009924 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009925 return 0;
9926 if (CastSrcTy) {
9927 if (I->getOperand(0)->getType() != CastSrcTy)
9928 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009929 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009930 // We can't sink the load if the loaded value could be modified between
9931 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009932 if (LI->isVolatile() != isVolatile ||
9933 LI->getParent() != PN.getIncomingBlock(i) ||
9934 !isSafeToSinkLoad(LI))
9935 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009936
9937 // If the PHI is volatile and its block has multiple successors, sinking
9938 // it would remove a load of the volatile value from the path through the
9939 // other successor.
9940 if (isVolatile &&
9941 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9942 return 0;
9943
9944
Chris Lattnerbac32862004-11-14 19:13:23 +00009945 } else if (I->getOperand(1) != ConstantOp) {
9946 return 0;
9947 }
9948 }
9949
9950 // Okay, they are all the same operation. Create a new PHI node of the
9951 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009952 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9953 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009954 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009955
9956 Value *InVal = FirstInst->getOperand(0);
9957 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009958
9959 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009960 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9961 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9962 if (NewInVal != InVal)
9963 InVal = 0;
9964 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9965 }
9966
9967 Value *PhiVal;
9968 if (InVal) {
9969 // The new PHI unions all of the same values together. This is really
9970 // common, so we handle it intelligently here for compile-time speed.
9971 PhiVal = InVal;
9972 delete NewPN;
9973 } else {
9974 InsertNewInstBefore(NewPN, PN);
9975 PhiVal = NewPN;
9976 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009977
Chris Lattnerbac32862004-11-14 19:13:23 +00009978 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009979 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009980 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009981 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009982 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009983 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009984 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009985 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009986 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9987
9988 // If this was a volatile load that we are merging, make sure to loop through
9989 // and mark all the input loads as non-volatile. If we don't do this, we will
9990 // insert a new volatile load and the old ones will not be deletable.
9991 if (isVolatile)
9992 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9993 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9994
9995 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009996}
Chris Lattnera1be5662002-05-02 17:06:02 +00009997
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009998/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9999/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010000static bool DeadPHICycle(PHINode *PN,
10001 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010002 if (PN->use_empty()) return true;
10003 if (!PN->hasOneUse()) return false;
10004
10005 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010006 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010007 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010008
10009 // Don't scan crazily complex things.
10010 if (PotentiallyDeadPHIs.size() == 16)
10011 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010012
10013 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10014 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010015
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010016 return false;
10017}
10018
Chris Lattnercf5008a2007-11-06 21:52:06 +000010019/// PHIsEqualValue - Return true if this phi node is always equal to
10020/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10021/// z = some value; x = phi (y, z); y = phi (x, z)
10022static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10023 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10024 // See if we already saw this PHI node.
10025 if (!ValueEqualPHIs.insert(PN))
10026 return true;
10027
10028 // Don't scan crazily complex things.
10029 if (ValueEqualPHIs.size() == 16)
10030 return false;
10031
10032 // Scan the operands to see if they are either phi nodes or are equal to
10033 // the value.
10034 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10035 Value *Op = PN->getIncomingValue(i);
10036 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10037 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10038 return false;
10039 } else if (Op != NonPhiInVal)
10040 return false;
10041 }
10042
10043 return true;
10044}
10045
10046
Chris Lattner473945d2002-05-06 18:06:38 +000010047// PHINode simplification
10048//
Chris Lattner7e708292002-06-25 16:13:24 +000010049Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010050 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010051 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010052
Owen Anderson7e057142006-07-10 22:03:18 +000010053 if (Value *V = PN.hasConstantValue())
10054 return ReplaceInstUsesWith(PN, V);
10055
Owen Anderson7e057142006-07-10 22:03:18 +000010056 // If all PHI operands are the same operation, pull them through the PHI,
10057 // reducing code size.
10058 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10059 PN.getIncomingValue(0)->hasOneUse())
10060 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10061 return Result;
10062
10063 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10064 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10065 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010066 if (PN.hasOneUse()) {
10067 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10068 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010069 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010070 PotentiallyDeadPHIs.insert(&PN);
10071 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10072 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10073 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010074
10075 // If this phi has a single use, and if that use just computes a value for
10076 // the next iteration of a loop, delete the phi. This occurs with unused
10077 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10078 // common case here is good because the only other things that catch this
10079 // are induction variable analysis (sometimes) and ADCE, which is only run
10080 // late.
10081 if (PHIUser->hasOneUse() &&
10082 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10083 PHIUser->use_back() == &PN) {
10084 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10085 }
10086 }
Owen Anderson7e057142006-07-10 22:03:18 +000010087
Chris Lattnercf5008a2007-11-06 21:52:06 +000010088 // We sometimes end up with phi cycles that non-obviously end up being the
10089 // same value, for example:
10090 // z = some value; x = phi (y, z); y = phi (x, z)
10091 // where the phi nodes don't necessarily need to be in the same block. Do a
10092 // quick check to see if the PHI node only contains a single non-phi value, if
10093 // so, scan to see if the phi cycle is actually equal to that value.
10094 {
10095 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10096 // Scan for the first non-phi operand.
10097 while (InValNo != NumOperandVals &&
10098 isa<PHINode>(PN.getIncomingValue(InValNo)))
10099 ++InValNo;
10100
10101 if (InValNo != NumOperandVals) {
10102 Value *NonPhiInVal = PN.getOperand(InValNo);
10103
10104 // Scan the rest of the operands to see if there are any conflicts, if so
10105 // there is no need to recursively scan other phis.
10106 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10107 Value *OpVal = PN.getIncomingValue(InValNo);
10108 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10109 break;
10110 }
10111
10112 // If we scanned over all operands, then we have one unique value plus
10113 // phi values. Scan PHI nodes to see if they all merge in each other or
10114 // the value.
10115 if (InValNo == NumOperandVals) {
10116 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10117 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10118 return ReplaceInstUsesWith(PN, NonPhiInVal);
10119 }
10120 }
10121 }
Chris Lattner60921c92003-12-19 05:58:40 +000010122 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010123}
10124
Reid Spencer17212df2006-12-12 09:18:51 +000010125static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10126 Instruction *InsertPoint,
10127 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010128 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10129 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010130 // We must cast correctly to the pointer type. Ensure that we
10131 // sign extend the integer value if it is smaller as this is
10132 // used for address computation.
10133 Instruction::CastOps opcode =
10134 (VTySize < PtrSize ? Instruction::SExt :
10135 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10136 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010137}
10138
Chris Lattnera1be5662002-05-02 17:06:02 +000010139
Chris Lattner7e708292002-06-25 16:13:24 +000010140Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010141 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010142 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010143 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010144 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010145 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010146
Chris Lattnere87597f2004-10-16 18:11:37 +000010147 if (isa<UndefValue>(GEP.getOperand(0)))
10148 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10149
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010150 bool HasZeroPointerIndex = false;
10151 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10152 HasZeroPointerIndex = C->isNullValue();
10153
10154 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010155 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010156
Chris Lattner28977af2004-04-05 01:30:19 +000010157 // Eliminate unneeded casts for indices.
10158 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010159
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010160 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010161 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010162 if (isa<SequentialType>(*GTI)) {
10163 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010164 if (CI->getOpcode() == Instruction::ZExt ||
10165 CI->getOpcode() == Instruction::SExt) {
10166 const Type *SrcTy = CI->getOperand(0)->getType();
10167 // We can eliminate a cast from i32 to i64 iff the target
10168 // is a 32-bit pointer target.
10169 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10170 MadeChange = true;
10171 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +000010172 }
10173 }
10174 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010175 // If we are using a wider index than needed for this platform, shrink it
10176 // to what we need. If the incoming value needs a cast instruction,
10177 // insert it. This explicit cast can make subsequent optimizations more
10178 // obvious.
10179 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010180 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010181 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010182 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +000010183 MadeChange = true;
10184 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010185 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10186 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010187 GEP.setOperand(i, Op);
10188 MadeChange = true;
10189 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010190 }
Chris Lattner28977af2004-04-05 01:30:19 +000010191 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010192 }
Chris Lattner28977af2004-04-05 01:30:19 +000010193 if (MadeChange) return &GEP;
10194
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010195 // If this GEP instruction doesn't move the pointer, and if the input operand
10196 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10197 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +000010198 if (GEP.hasAllZeroIndices()) {
10199 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10200 // If the bitcast is of an allocation, and the allocation will be
10201 // converted to match the type of the cast, don't touch this.
10202 if (isa<AllocationInst>(BCI->getOperand(0))) {
10203 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +000010204 if (Instruction *I = visitBitCast(*BCI)) {
10205 if (I != BCI) {
10206 I->takeName(BCI);
10207 BCI->getParent()->getInstList().insert(BCI, I);
10208 ReplaceInstUsesWith(*BCI, I);
10209 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010210 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +000010211 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010212 }
10213 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10214 }
10215 }
10216
Chris Lattner90ac28c2002-08-02 19:29:35 +000010217 // Combine Indices - If the source pointer to this getelementptr instruction
10218 // is a getelementptr instruction, combine the indices of the two
10219 // getelementptr instructions into a single instruction.
10220 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010221 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010222 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010223 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010224
10225 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010226 // Note that if our source is a gep chain itself that we wait for that
10227 // chain to be resolved before we perform this transformation. This
10228 // avoids us creating a TON of code in some cases.
10229 //
10230 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10231 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10232 return 0; // Wait until our source is folded to completion.
10233
Chris Lattner72588fc2007-02-15 22:48:32 +000010234 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010235
10236 // Find out whether the last index in the source GEP is a sequential idx.
10237 bool EndsWithSequential = false;
10238 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10239 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010240 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010241
Chris Lattner90ac28c2002-08-02 19:29:35 +000010242 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010243 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010244 // Replace: gep (gep %P, long B), long A, ...
10245 // With: T = long A+B; gep %P, T, ...
10246 //
Chris Lattner620ce142004-05-07 22:09:22 +000010247 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010248 if (SO1 == Constant::getNullValue(SO1->getType())) {
10249 Sum = GO1;
10250 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10251 Sum = SO1;
10252 } else {
10253 // If they aren't the same type, convert both to an integer of the
10254 // target's pointer size.
10255 if (SO1->getType() != GO1->getType()) {
10256 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010257 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010258 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010259 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010260 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010261 unsigned PS = TD->getPointerSizeInBits();
10262 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010263 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010264 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010265
Duncan Sands514ab342007-11-01 20:53:16 +000010266 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010267 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010268 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010269 } else {
10270 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010271 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10272 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010273 }
10274 }
10275 }
Chris Lattner620ce142004-05-07 22:09:22 +000010276 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10277 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10278 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010279 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010280 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010281 }
Chris Lattner28977af2004-04-05 01:30:19 +000010282 }
Chris Lattner620ce142004-05-07 22:09:22 +000010283
10284 // Recycle the GEP we already have if possible.
10285 if (SrcGEPOperands.size() == 2) {
10286 GEP.setOperand(0, SrcGEPOperands[0]);
10287 GEP.setOperand(1, Sum);
10288 return &GEP;
10289 } else {
10290 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10291 SrcGEPOperands.end()-1);
10292 Indices.push_back(Sum);
10293 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10294 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010295 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010296 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010297 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010298 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010299 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10300 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010301 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10302 }
10303
10304 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010305 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10306 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010307
Chris Lattner620ce142004-05-07 22:09:22 +000010308 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010309 // GEP of global variable. If all of the indices for this GEP are
10310 // constants, we can promote this to a constexpr instead of an instruction.
10311
10312 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010313 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010314 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10315 for (; I != E && isa<Constant>(*I); ++I)
10316 Indices.push_back(cast<Constant>(*I));
10317
10318 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010319 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10320 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010321
10322 // Replace all uses of the GEP with the new constexpr...
10323 return ReplaceInstUsesWith(GEP, CE);
10324 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010325 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010326 if (!isa<PointerType>(X->getType())) {
10327 // Not interesting. Source pointer must be a cast from pointer.
10328 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010329 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10330 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010331 //
10332 // This occurs when the program declares an array extern like "int X[];"
10333 //
10334 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10335 const PointerType *XTy = cast<PointerType>(X->getType());
10336 if (const ArrayType *XATy =
10337 dyn_cast<ArrayType>(XTy->getElementType()))
10338 if (const ArrayType *CATy =
10339 dyn_cast<ArrayType>(CPTy->getElementType()))
10340 if (CATy->getElementType() == XATy->getElementType()) {
10341 // At this point, we know that the cast source type is a pointer
10342 // to an array of the same type as the destination pointer
10343 // array. Because the array type is never stepped over (there
10344 // is a leading zero) we can fold the cast into this GEP.
10345 GEP.setOperand(0, X);
10346 return &GEP;
10347 }
10348 } else if (GEP.getNumOperands() == 2) {
10349 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010350 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10351 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010352 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10353 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10354 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +000010355 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10356 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010357 Value *Idx[2];
10358 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10359 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010360 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010361 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010362 // V and GEP are both pointer types --> BitCast
10363 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010364 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010365
10366 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010367 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010368 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010369 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010370
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010371 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010372 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +000010373 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010374
10375 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10376 // allow either a mul, shift, or constant here.
10377 Value *NewIdx = 0;
10378 ConstantInt *Scale = 0;
10379 if (ArrayEltSize == 1) {
10380 NewIdx = GEP.getOperand(1);
10381 Scale = ConstantInt::get(NewIdx->getType(), 1);
10382 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010383 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010384 Scale = CI;
10385 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10386 if (Inst->getOpcode() == Instruction::Shl &&
10387 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010388 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10389 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10390 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010391 NewIdx = Inst->getOperand(0);
10392 } else if (Inst->getOpcode() == Instruction::Mul &&
10393 isa<ConstantInt>(Inst->getOperand(1))) {
10394 Scale = cast<ConstantInt>(Inst->getOperand(1));
10395 NewIdx = Inst->getOperand(0);
10396 }
10397 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010398
Chris Lattner7835cdd2005-09-13 18:36:04 +000010399 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010400 // out, perform the transformation. Note, we don't know whether Scale is
10401 // signed or not. We'll use unsigned version of division/modulo
10402 // operation after making sure Scale doesn't have the sign bit set.
10403 if (Scale && Scale->getSExtValue() >= 0LL &&
10404 Scale->getZExtValue() % ArrayEltSize == 0) {
10405 Scale = ConstantInt::get(Scale->getType(),
10406 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010407 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010408 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010409 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010410 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010411 NewIdx = InsertNewInstBefore(Sc, GEP);
10412 }
10413
10414 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010415 Value *Idx[2];
10416 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10417 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010418 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010419 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010420 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10421 // The NewGEP must be pointer typed, so must the old one -> BitCast
10422 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010423 }
10424 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010425 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010426 }
10427
Chris Lattner8a2a3112001-12-14 16:52:21 +000010428 return 0;
10429}
10430
Chris Lattner0864acf2002-11-04 16:18:53 +000010431Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10432 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010433 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010434 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10435 const Type *NewTy =
10436 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010437 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010438
10439 // Create and insert the replacement instruction...
10440 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010441 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010442 else {
10443 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010444 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010445 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010446
10447 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010448
Chris Lattner0864acf2002-11-04 16:18:53 +000010449 // Scan to the end of the allocation instructions, to skip over a block of
10450 // allocas if possible...
10451 //
10452 BasicBlock::iterator It = New;
10453 while (isa<AllocationInst>(*It)) ++It;
10454
10455 // Now that I is pointing to the first non-allocation-inst in the block,
10456 // insert our getelementptr instruction...
10457 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010458 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010459 Value *Idx[2];
10460 Idx[0] = NullIdx;
10461 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010462 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10463 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010464
10465 // Now make everything use the getelementptr instead of the original
10466 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010467 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010468 } else if (isa<UndefValue>(AI.getArraySize())) {
10469 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010470 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010471 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010472
10473 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10474 // Note that we only do this for alloca's, because malloc should allocate and
10475 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010476 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010477 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010478 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10479
Chris Lattner0864acf2002-11-04 16:18:53 +000010480 return 0;
10481}
10482
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010483Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10484 Value *Op = FI.getOperand(0);
10485
Chris Lattner17be6352004-10-18 02:59:09 +000010486 // free undef -> unreachable.
10487 if (isa<UndefValue>(Op)) {
10488 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010489 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010490 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010491 return EraseInstFromFunction(FI);
10492 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010493
Chris Lattner6160e852004-02-28 04:57:37 +000010494 // If we have 'free null' delete the instruction. This can happen in stl code
10495 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010496 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010497 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010498
10499 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10500 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10501 FI.setOperand(0, CI->getOperand(0));
10502 return &FI;
10503 }
10504
10505 // Change free (gep X, 0,0,0,0) into free(X)
10506 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10507 if (GEPI->hasAllZeroIndices()) {
10508 AddToWorkList(GEPI);
10509 FI.setOperand(0, GEPI->getOperand(0));
10510 return &FI;
10511 }
10512 }
10513
10514 // Change free(malloc) into nothing, if the malloc has a single use.
10515 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10516 if (MI->hasOneUse()) {
10517 EraseInstFromFunction(FI);
10518 return EraseInstFromFunction(*MI);
10519 }
Chris Lattner6160e852004-02-28 04:57:37 +000010520
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010521 return 0;
10522}
10523
10524
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010525/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010526static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010527 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010528 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010529 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010530
Devang Patel99db6ad2007-10-18 19:52:32 +000010531 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10532 // Instead of loading constant c string, use corresponding integer value
10533 // directly if string length is small enough.
10534 const std::string &Str = CE->getOperand(0)->getStringValue();
10535 if (!Str.empty()) {
10536 unsigned len = Str.length();
10537 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10538 unsigned numBits = Ty->getPrimitiveSizeInBits();
10539 // Replace LI with immediate integer store.
10540 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010541 APInt StrVal(numBits, 0);
10542 APInt SingleChar(numBits, 0);
10543 if (TD->isLittleEndian()) {
10544 for (signed i = len-1; i >= 0; i--) {
10545 SingleChar = (uint64_t) Str[i];
10546 StrVal = (StrVal << 8) | SingleChar;
10547 }
10548 } else {
10549 for (unsigned i = 0; i < len; i++) {
10550 SingleChar = (uint64_t) Str[i];
10551 StrVal = (StrVal << 8) | SingleChar;
10552 }
10553 // Append NULL at the end.
10554 SingleChar = 0;
10555 StrVal = (StrVal << 8) | SingleChar;
10556 }
10557 Value *NL = ConstantInt::get(StrVal);
10558 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010559 }
10560 }
10561 }
10562
Chris Lattnerb89e0712004-07-13 01:49:43 +000010563 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010564 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010565 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010566
Reid Spencer42230162007-01-22 05:51:25 +000010567 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010568 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010569 // If the source is an array, the code below will not succeed. Check to
10570 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10571 // constants.
10572 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10573 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10574 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010575 Value *Idxs[2];
10576 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10577 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010578 SrcTy = cast<PointerType>(CastOp->getType());
10579 SrcPTy = SrcTy->getElementType();
10580 }
10581
Reid Spencer42230162007-01-22 05:51:25 +000010582 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010583 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010584 // Do not allow turning this into a load of an integer, which is then
10585 // casted to a pointer, this pessimizes pointer analysis a lot.
10586 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010587 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10588 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010589
Chris Lattnerf9527852005-01-31 04:50:46 +000010590 // Okay, we are casting from one integer or pointer type to another of
10591 // the same size. Instead of casting the pointer before the load, cast
10592 // the result of the loaded value.
10593 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10594 CI->getName(),
10595 LI.isVolatile()),LI);
10596 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010597 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010598 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010599 }
10600 }
10601 return 0;
10602}
10603
Chris Lattnerc10aced2004-09-19 18:43:46 +000010604/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010605/// from this value cannot trap. If it is not obviously safe to load from the
10606/// specified pointer, we do a quick local scan of the basic block containing
10607/// ScanFrom, to determine if the address is already accessed.
10608static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010609 // If it is an alloca it is always safe to load from.
10610 if (isa<AllocaInst>(V)) return true;
10611
Duncan Sands46318cd2007-09-19 10:25:38 +000010612 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010613 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010614 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010615 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010616
10617 // Otherwise, be a little bit agressive by scanning the local block where we
10618 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010619 // from/to. If so, the previous load or store would have already trapped,
10620 // so there is no harm doing an extra load (also, CSE will later eliminate
10621 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010622 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10623
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010624 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010625 --BBI;
10626
10627 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10628 if (LI->getOperand(0) == V) return true;
10629 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10630 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010631
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010632 }
Chris Lattner8a375202004-09-19 19:18:10 +000010633 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010634}
10635
Chris Lattner8d2e8882007-08-11 18:48:48 +000010636/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10637/// until we find the underlying object a pointer is referring to or something
10638/// we don't understand. Note that the returned pointer may be offset from the
10639/// input, because we ignore GEP indices.
10640static Value *GetUnderlyingObject(Value *Ptr) {
10641 while (1) {
10642 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10643 if (CE->getOpcode() == Instruction::BitCast ||
10644 CE->getOpcode() == Instruction::GetElementPtr)
10645 Ptr = CE->getOperand(0);
10646 else
10647 return Ptr;
10648 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10649 Ptr = BCI->getOperand(0);
10650 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10651 Ptr = GEP->getOperand(0);
10652 } else {
10653 return Ptr;
10654 }
10655 }
10656}
10657
Chris Lattner833b8a42003-06-26 05:06:25 +000010658Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10659 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010660
Dan Gohman9941f742007-07-20 16:34:21 +000010661 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010662 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10663 if (KnownAlign >
10664 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10665 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010666 LI.setAlignment(KnownAlign);
10667
Chris Lattner37366c12005-05-01 04:24:53 +000010668 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010669 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010670 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010671 return Res;
10672
10673 // None of the following transforms are legal for volatile loads.
10674 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010675
Chris Lattner62f254d2005-09-12 22:00:15 +000010676 if (&LI.getParent()->front() != &LI) {
10677 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010678 // If the instruction immediately before this is a store to the same
10679 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010680 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10681 if (SI->getOperand(1) == LI.getOperand(0))
10682 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010683 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10684 if (LIB->getOperand(0) == LI.getOperand(0))
10685 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010686 }
Chris Lattner37366c12005-05-01 04:24:53 +000010687
Christopher Lambb15147e2007-12-29 07:56:53 +000010688 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10689 const Value *GEPI0 = GEPI->getOperand(0);
10690 // TODO: Consider a target hook for valid address spaces for this xform.
10691 if (isa<ConstantPointerNull>(GEPI0) &&
10692 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010693 // Insert a new store to null instruction before the load to indicate
10694 // that this code is not reachable. We do this instead of inserting
10695 // an unreachable instruction directly because we cannot modify the
10696 // CFG.
10697 new StoreInst(UndefValue::get(LI.getType()),
10698 Constant::getNullValue(Op->getType()), &LI);
10699 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10700 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010701 }
Chris Lattner37366c12005-05-01 04:24:53 +000010702
Chris Lattnere87597f2004-10-16 18:11:37 +000010703 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010704 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010705 // TODO: Consider a target hook for valid address spaces for this xform.
10706 if (isa<UndefValue>(C) || (C->isNullValue() &&
10707 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010708 // Insert a new store to null instruction before the load to indicate that
10709 // this code is not reachable. We do this instead of inserting an
10710 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010711 new StoreInst(UndefValue::get(LI.getType()),
10712 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010713 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010714 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010715
Chris Lattnere87597f2004-10-16 18:11:37 +000010716 // Instcombine load (constant global) into the value loaded.
10717 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010718 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010719 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010720
Chris Lattnere87597f2004-10-16 18:11:37 +000010721 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010722 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010723 if (CE->getOpcode() == Instruction::GetElementPtr) {
10724 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010725 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010726 if (Constant *V =
10727 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010728 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010729 if (CE->getOperand(0)->isNullValue()) {
10730 // Insert a new store to null instruction before the load to indicate
10731 // that this code is not reachable. We do this instead of inserting
10732 // an unreachable instruction directly because we cannot modify the
10733 // CFG.
10734 new StoreInst(UndefValue::get(LI.getType()),
10735 Constant::getNullValue(Op->getType()), &LI);
10736 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10737 }
10738
Reid Spencer3da59db2006-11-27 01:05:10 +000010739 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010740 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010741 return Res;
10742 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010743 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010744 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010745
10746 // If this load comes from anywhere in a constant global, and if the global
10747 // is all undef or zero, we know what it loads.
10748 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10749 if (GV->isConstant() && GV->hasInitializer()) {
10750 if (GV->getInitializer()->isNullValue())
10751 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10752 else if (isa<UndefValue>(GV->getInitializer()))
10753 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10754 }
10755 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010756
Chris Lattner37366c12005-05-01 04:24:53 +000010757 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010758 // Change select and PHI nodes to select values instead of addresses: this
10759 // helps alias analysis out a lot, allows many others simplifications, and
10760 // exposes redundancy in the code.
10761 //
10762 // Note that we cannot do the transformation unless we know that the
10763 // introduced loads cannot trap! Something like this is valid as long as
10764 // the condition is always false: load (select bool %C, int* null, int* %G),
10765 // but it would not be valid if we transformed it to load from null
10766 // unconditionally.
10767 //
10768 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10769 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010770 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10771 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010772 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010773 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010774 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010775 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010776 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010777 }
10778
Chris Lattner684fe212004-09-23 15:46:00 +000010779 // load (select (cond, null, P)) -> load P
10780 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10781 if (C->isNullValue()) {
10782 LI.setOperand(0, SI->getOperand(2));
10783 return &LI;
10784 }
10785
10786 // load (select (cond, P, null)) -> load P
10787 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10788 if (C->isNullValue()) {
10789 LI.setOperand(0, SI->getOperand(1));
10790 return &LI;
10791 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010792 }
10793 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010794 return 0;
10795}
10796
Reid Spencer55af2b52007-01-19 21:20:31 +000010797/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010798/// when possible.
10799static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10800 User *CI = cast<User>(SI.getOperand(1));
10801 Value *CastOp = CI->getOperand(0);
10802
10803 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10804 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10805 const Type *SrcPTy = SrcTy->getElementType();
10806
Reid Spencer42230162007-01-22 05:51:25 +000010807 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010808 // If the source is an array, the code below will not succeed. Check to
10809 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10810 // constants.
10811 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10812 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10813 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010814 Value* Idxs[2];
10815 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10816 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010817 SrcTy = cast<PointerType>(CastOp->getType());
10818 SrcPTy = SrcTy->getElementType();
10819 }
10820
Reid Spencer67f827c2007-01-20 23:35:48 +000010821 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10822 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10823 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010824
10825 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010826 // the same size. Instead of casting the pointer before
10827 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010828 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010829 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010830 Instruction::CastOps opcode = Instruction::BitCast;
10831 const Type* CastSrcTy = SIOp0->getType();
10832 const Type* CastDstTy = SrcPTy;
10833 if (isa<PointerType>(CastDstTy)) {
10834 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010835 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010836 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010837 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010838 opcode = Instruction::PtrToInt;
10839 }
10840 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010841 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010842 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010843 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010844 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010845 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010846 return new StoreInst(NewCast, CastOp);
10847 }
10848 }
10849 }
10850 return 0;
10851}
10852
Chris Lattner2f503e62005-01-31 05:36:43 +000010853Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10854 Value *Val = SI.getOperand(0);
10855 Value *Ptr = SI.getOperand(1);
10856
10857 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010858 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010859 ++NumCombined;
10860 return 0;
10861 }
Chris Lattner836692d2007-01-15 06:51:56 +000010862
10863 // If the RHS is an alloca with a single use, zapify the store, making the
10864 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010865 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010866 if (isa<AllocaInst>(Ptr)) {
10867 EraseInstFromFunction(SI);
10868 ++NumCombined;
10869 return 0;
10870 }
10871
10872 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10873 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10874 GEP->getOperand(0)->hasOneUse()) {
10875 EraseInstFromFunction(SI);
10876 ++NumCombined;
10877 return 0;
10878 }
10879 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010880
Dan Gohman9941f742007-07-20 16:34:21 +000010881 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010882 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10883 if (KnownAlign >
10884 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10885 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010886 SI.setAlignment(KnownAlign);
10887
Chris Lattner9ca96412006-02-08 03:25:32 +000010888 // Do really simple DSE, to catch cases where there are several consequtive
10889 // stores to the same location, separated by a few arithmetic operations. This
10890 // situation often occurs with bitfield accesses.
10891 BasicBlock::iterator BBI = &SI;
10892 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10893 --ScanInsts) {
10894 --BBI;
10895
10896 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10897 // Prev store isn't volatile, and stores to the same location?
10898 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10899 ++NumDeadStore;
10900 ++BBI;
10901 EraseInstFromFunction(*PrevSI);
10902 continue;
10903 }
10904 break;
10905 }
10906
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010907 // If this is a load, we have to stop. However, if the loaded value is from
10908 // the pointer we're loading and is producing the pointer we're storing,
10909 // then *this* store is dead (X = load P; store X -> P).
10910 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010911 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010912 EraseInstFromFunction(SI);
10913 ++NumCombined;
10914 return 0;
10915 }
10916 // Otherwise, this is a load from some other location. Stores before it
10917 // may not be dead.
10918 break;
10919 }
10920
Chris Lattner9ca96412006-02-08 03:25:32 +000010921 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010922 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010923 break;
10924 }
10925
10926
10927 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010928
10929 // store X, null -> turns into 'unreachable' in SimplifyCFG
10930 if (isa<ConstantPointerNull>(Ptr)) {
10931 if (!isa<UndefValue>(Val)) {
10932 SI.setOperand(0, UndefValue::get(Val->getType()));
10933 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010934 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010935 ++NumCombined;
10936 }
10937 return 0; // Do not modify these!
10938 }
10939
10940 // store undef, Ptr -> noop
10941 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010942 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010943 ++NumCombined;
10944 return 0;
10945 }
10946
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010947 // If the pointer destination is a cast, see if we can fold the cast into the
10948 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010949 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010950 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10951 return Res;
10952 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010953 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010954 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10955 return Res;
10956
Chris Lattner408902b2005-09-12 23:23:25 +000010957
10958 // If this store is the last instruction in the basic block, and if the block
10959 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010960 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010961 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010962 if (BI->isUnconditional())
10963 if (SimplifyStoreAtEndOfBlock(SI))
10964 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010965
Chris Lattner2f503e62005-01-31 05:36:43 +000010966 return 0;
10967}
10968
Chris Lattner3284d1f2007-04-15 00:07:55 +000010969/// SimplifyStoreAtEndOfBlock - Turn things like:
10970/// if () { *P = v1; } else { *P = v2 }
10971/// into a phi node with a store in the successor.
10972///
Chris Lattner31755a02007-04-15 01:02:18 +000010973/// Simplify things like:
10974/// *P = v1; if () { *P = v2; }
10975/// into a phi node with a store in the successor.
10976///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010977bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10978 BasicBlock *StoreBB = SI.getParent();
10979
10980 // Check to see if the successor block has exactly two incoming edges. If
10981 // so, see if the other predecessor contains a store to the same location.
10982 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010983 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010984
10985 // Determine whether Dest has exactly two predecessors and, if so, compute
10986 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010987 pred_iterator PI = pred_begin(DestBB);
10988 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010989 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010990 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010991 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010992 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010993 return false;
10994
10995 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010996 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010997 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010998 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010999 }
Chris Lattner31755a02007-04-15 01:02:18 +000011000 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011001 return false;
11002
11003
Chris Lattner31755a02007-04-15 01:02:18 +000011004 // Verify that the other block ends in a branch and is not otherwise empty.
11005 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011006 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011007 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011008 return false;
11009
Chris Lattner31755a02007-04-15 01:02:18 +000011010 // If the other block ends in an unconditional branch, check for the 'if then
11011 // else' case. there is an instruction before the branch.
11012 StoreInst *OtherStore = 0;
11013 if (OtherBr->isUnconditional()) {
11014 // If this isn't a store, or isn't a store to the same location, bail out.
11015 --BBI;
11016 OtherStore = dyn_cast<StoreInst>(BBI);
11017 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11018 return false;
11019 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011020 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011021 // destinations is StoreBB, then we have the if/then case.
11022 if (OtherBr->getSuccessor(0) != StoreBB &&
11023 OtherBr->getSuccessor(1) != StoreBB)
11024 return false;
11025
11026 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011027 // if/then triangle. See if there is a store to the same ptr as SI that
11028 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011029 for (;; --BBI) {
11030 // Check to see if we find the matching store.
11031 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11032 if (OtherStore->getOperand(1) != SI.getOperand(1))
11033 return false;
11034 break;
11035 }
Chris Lattnerd717c182007-05-05 22:32:24 +000011036 // If we find something that may be using the stored value, or if we run
11037 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000011038 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11039 BBI == OtherBB->begin())
11040 return false;
11041 }
11042
11043 // In order to eliminate the store in OtherBr, we have to
11044 // make sure nothing reads the stored value in StoreBB.
11045 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11046 // FIXME: This should really be AA driven.
11047 if (isa<LoadInst>(I) || I->mayWriteToMemory())
11048 return false;
11049 }
11050 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011051
Chris Lattner31755a02007-04-15 01:02:18 +000011052 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011053 Value *MergedVal = OtherStore->getOperand(0);
11054 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011055 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011056 PN->reserveOperandSpace(2);
11057 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011058 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11059 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011060 }
11061
11062 // Advance to a place where it is safe to insert the new store and
11063 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000011064 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011065 while (isa<PHINode>(BBI)) ++BBI;
11066 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11067 OtherStore->isVolatile()), *BBI);
11068
11069 // Nuke the old stores.
11070 EraseInstFromFunction(SI);
11071 EraseInstFromFunction(*OtherStore);
11072 ++NumCombined;
11073 return true;
11074}
11075
Chris Lattner2f503e62005-01-31 05:36:43 +000011076
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011077Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11078 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011079 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011080 BasicBlock *TrueDest;
11081 BasicBlock *FalseDest;
11082 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11083 !isa<Constant>(X)) {
11084 // Swap Destinations and condition...
11085 BI.setCondition(X);
11086 BI.setSuccessor(0, FalseDest);
11087 BI.setSuccessor(1, TrueDest);
11088 return &BI;
11089 }
11090
Reid Spencere4d87aa2006-12-23 06:05:41 +000011091 // Cannonicalize fcmp_one -> fcmp_oeq
11092 FCmpInst::Predicate FPred; Value *Y;
11093 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11094 TrueDest, FalseDest)))
11095 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11096 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11097 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011098 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011099 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11100 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011101 // Swap Destinations and condition...
11102 BI.setCondition(NewSCC);
11103 BI.setSuccessor(0, FalseDest);
11104 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011105 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011106 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011107 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011108 return &BI;
11109 }
11110
11111 // Cannonicalize icmp_ne -> icmp_eq
11112 ICmpInst::Predicate IPred;
11113 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11114 TrueDest, FalseDest)))
11115 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11116 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11117 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11118 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011119 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011120 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11121 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011122 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011123 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011124 BI.setSuccessor(0, FalseDest);
11125 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011126 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011127 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011128 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011129 return &BI;
11130 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011131
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011132 return 0;
11133}
Chris Lattner0864acf2002-11-04 16:18:53 +000011134
Chris Lattner46238a62004-07-03 00:26:11 +000011135Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11136 Value *Cond = SI.getCondition();
11137 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11138 if (I->getOpcode() == Instruction::Add)
11139 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11140 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11141 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011142 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011143 AddRHS));
11144 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011145 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011146 return &SI;
11147 }
11148 }
11149 return 0;
11150}
11151
Chris Lattner220b0cf2006-03-05 00:22:33 +000011152/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11153/// is to leave as a vector operation.
11154static bool CheapToScalarize(Value *V, bool isConstant) {
11155 if (isa<ConstantAggregateZero>(V))
11156 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011157 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011158 if (isConstant) return true;
11159 // If all elts are the same, we can extract.
11160 Constant *Op0 = C->getOperand(0);
11161 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11162 if (C->getOperand(i) != Op0)
11163 return false;
11164 return true;
11165 }
11166 Instruction *I = dyn_cast<Instruction>(V);
11167 if (!I) return false;
11168
11169 // Insert element gets simplified to the inserted element or is deleted if
11170 // this is constant idx extract element and its a constant idx insertelt.
11171 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11172 isa<ConstantInt>(I->getOperand(2)))
11173 return true;
11174 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11175 return true;
11176 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11177 if (BO->hasOneUse() &&
11178 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11179 CheapToScalarize(BO->getOperand(1), isConstant)))
11180 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011181 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11182 if (CI->hasOneUse() &&
11183 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11184 CheapToScalarize(CI->getOperand(1), isConstant)))
11185 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011186
11187 return false;
11188}
11189
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011190/// Read and decode a shufflevector mask.
11191///
11192/// It turns undef elements into values that are larger than the number of
11193/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011194static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11195 unsigned NElts = SVI->getType()->getNumElements();
11196 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11197 return std::vector<unsigned>(NElts, 0);
11198 if (isa<UndefValue>(SVI->getOperand(2)))
11199 return std::vector<unsigned>(NElts, 2*NElts);
11200
11201 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011202 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000011203 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11204 if (isa<UndefValue>(CP->getOperand(i)))
11205 Result.push_back(NElts*2); // undef -> 8
11206 else
Reid Spencerb83eb642006-10-20 07:07:24 +000011207 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011208 return Result;
11209}
11210
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011211/// FindScalarElement - Given a vector and an element number, see if the scalar
11212/// value is already around as a register, for example if it were inserted then
11213/// extracted from the vector.
11214static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011215 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11216 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011217 unsigned Width = PTy->getNumElements();
11218 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011219 return UndefValue::get(PTy->getElementType());
11220
11221 if (isa<UndefValue>(V))
11222 return UndefValue::get(PTy->getElementType());
11223 else if (isa<ConstantAggregateZero>(V))
11224 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011225 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011226 return CP->getOperand(EltNo);
11227 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11228 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011229 if (!isa<ConstantInt>(III->getOperand(2)))
11230 return 0;
11231 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011232
11233 // If this is an insert to the element we are looking for, return the
11234 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011235 if (EltNo == IIElt)
11236 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011237
11238 // Otherwise, the insertelement doesn't modify the value, recurse on its
11239 // vector input.
11240 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011241 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000011242 unsigned InEl = getShuffleMask(SVI)[EltNo];
11243 if (InEl < Width)
11244 return FindScalarElement(SVI->getOperand(0), InEl);
11245 else if (InEl < Width*2)
11246 return FindScalarElement(SVI->getOperand(1), InEl - Width);
11247 else
11248 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011249 }
11250
11251 // Otherwise, we don't know.
11252 return 0;
11253}
11254
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011255Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011256
Dan Gohman07a96762007-07-16 14:29:03 +000011257 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011258 if (isa<UndefValue>(EI.getOperand(0)))
11259 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11260
Dan Gohman07a96762007-07-16 14:29:03 +000011261 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011262 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11263 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11264
Reid Spencer9d6565a2007-02-15 02:26:10 +000011265 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000011266 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011267 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000011268 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011269 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011270 if (C->getOperand(i) != op0) {
11271 op0 = 0;
11272 break;
11273 }
11274 if (op0)
11275 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011276 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011277
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011278 // If extracting a specified index from the vector, see if we can recursively
11279 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011280 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011281 unsigned IndexVal = IdxC->getZExtValue();
11282 unsigned VectorWidth =
11283 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11284
11285 // If this is extracting an invalid index, turn this into undef, to avoid
11286 // crashing the code below.
11287 if (IndexVal >= VectorWidth)
11288 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11289
Chris Lattner867b99f2006-10-05 06:55:50 +000011290 // This instruction only demands the single element from the input vector.
11291 // If the input vector has a single use, simplify it based on this use
11292 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011293 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011294 uint64_t UndefElts;
11295 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011296 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011297 UndefElts)) {
11298 EI.setOperand(0, V);
11299 return &EI;
11300 }
11301 }
11302
Reid Spencerb83eb642006-10-20 07:07:24 +000011303 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011304 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011305
11306 // If the this extractelement is directly using a bitcast from a vector of
11307 // the same number of elements, see if we can find the source element from
11308 // it. In this case, we will end up needing to bitcast the scalars.
11309 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11310 if (const VectorType *VT =
11311 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11312 if (VT->getNumElements() == VectorWidth)
11313 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11314 return new BitCastInst(Elt, EI.getType());
11315 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011316 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011317
Chris Lattner73fa49d2006-05-25 22:53:38 +000011318 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011319 if (I->hasOneUse()) {
11320 // Push extractelement into predecessor operation if legal and
11321 // profitable to do so
11322 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011323 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11324 if (CheapToScalarize(BO, isConstantElt)) {
11325 ExtractElementInst *newEI0 =
11326 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11327 EI.getName()+".lhs");
11328 ExtractElementInst *newEI1 =
11329 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11330 EI.getName()+".rhs");
11331 InsertNewInstBefore(newEI0, EI);
11332 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011333 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011334 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011335 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011336 unsigned AS =
11337 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011338 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11339 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011340 GetElementPtrInst *GEP =
11341 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011342 InsertNewInstBefore(GEP, EI);
11343 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011344 }
11345 }
11346 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11347 // Extracting the inserted element?
11348 if (IE->getOperand(2) == EI.getOperand(1))
11349 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11350 // If the inserted and extracted elements are constants, they must not
11351 // be the same value, extract from the pre-inserted value instead.
11352 if (isa<Constant>(IE->getOperand(2)) &&
11353 isa<Constant>(EI.getOperand(1))) {
11354 AddUsesToWorkList(EI);
11355 EI.setOperand(0, IE->getOperand(0));
11356 return &EI;
11357 }
11358 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11359 // If this is extracting an element from a shufflevector, figure out where
11360 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011361 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11362 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011363 Value *Src;
11364 if (SrcIdx < SVI->getType()->getNumElements())
11365 Src = SVI->getOperand(0);
11366 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11367 SrcIdx -= SVI->getType()->getNumElements();
11368 Src = SVI->getOperand(1);
11369 } else {
11370 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011371 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011372 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011373 }
11374 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011375 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011376 return 0;
11377}
11378
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011379/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11380/// elements from either LHS or RHS, return the shuffle mask and true.
11381/// Otherwise, return false.
11382static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11383 std::vector<Constant*> &Mask) {
11384 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11385 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011386 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011387
11388 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011389 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011390 return true;
11391 } else if (V == LHS) {
11392 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011393 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011394 return true;
11395 } else if (V == RHS) {
11396 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011397 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011398 return true;
11399 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11400 // If this is an insert of an extract from some other vector, include it.
11401 Value *VecOp = IEI->getOperand(0);
11402 Value *ScalarOp = IEI->getOperand(1);
11403 Value *IdxOp = IEI->getOperand(2);
11404
Chris Lattnerd929f062006-04-27 21:14:21 +000011405 if (!isa<ConstantInt>(IdxOp))
11406 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011407 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011408
11409 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11410 // Okay, we can handle this if the vector we are insertinting into is
11411 // transitively ok.
11412 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11413 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011414 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011415 return true;
11416 }
11417 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11418 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011419 EI->getOperand(0)->getType() == V->getType()) {
11420 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011421 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011422
11423 // This must be extracting from either LHS or RHS.
11424 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11425 // Okay, we can handle this if the vector we are insertinting into is
11426 // transitively ok.
11427 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11428 // If so, update the mask to reflect the inserted value.
11429 if (EI->getOperand(0) == LHS) {
11430 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011431 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011432 } else {
11433 assert(EI->getOperand(0) == RHS);
11434 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011435 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011436
11437 }
11438 return true;
11439 }
11440 }
11441 }
11442 }
11443 }
11444 // TODO: Handle shufflevector here!
11445
11446 return false;
11447}
11448
11449/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11450/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11451/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011452static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011453 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011454 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011455 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011456 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011457 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011458
11459 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011460 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011461 return V;
11462 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011463 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011464 return V;
11465 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11466 // If this is an insert of an extract from some other vector, include it.
11467 Value *VecOp = IEI->getOperand(0);
11468 Value *ScalarOp = IEI->getOperand(1);
11469 Value *IdxOp = IEI->getOperand(2);
11470
11471 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11472 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11473 EI->getOperand(0)->getType() == V->getType()) {
11474 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011475 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11476 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011477
11478 // Either the extracted from or inserted into vector must be RHSVec,
11479 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011480 if (EI->getOperand(0) == RHS || RHS == 0) {
11481 RHS = EI->getOperand(0);
11482 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011483 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011484 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011485 return V;
11486 }
11487
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011488 if (VecOp == RHS) {
11489 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011490 // Everything but the extracted element is replaced with the RHS.
11491 for (unsigned i = 0; i != NumElts; ++i) {
11492 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011493 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011494 }
11495 return V;
11496 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011497
11498 // If this insertelement is a chain that comes from exactly these two
11499 // vectors, return the vector and the effective shuffle.
11500 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11501 return EI->getOperand(0);
11502
Chris Lattnerefb47352006-04-15 01:39:45 +000011503 }
11504 }
11505 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011506 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011507
11508 // Otherwise, can't do anything fancy. Return an identity vector.
11509 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011510 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011511 return V;
11512}
11513
11514Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11515 Value *VecOp = IE.getOperand(0);
11516 Value *ScalarOp = IE.getOperand(1);
11517 Value *IdxOp = IE.getOperand(2);
11518
Chris Lattner599ded12007-04-09 01:11:16 +000011519 // Inserting an undef or into an undefined place, remove this.
11520 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11521 ReplaceInstUsesWith(IE, VecOp);
11522
Chris Lattnerefb47352006-04-15 01:39:45 +000011523 // If the inserted element was extracted from some other vector, and if the
11524 // indexes are constant, try to turn this into a shufflevector operation.
11525 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11526 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11527 EI->getOperand(0)->getType() == IE.getType()) {
11528 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011529 unsigned ExtractedIdx =
11530 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011531 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011532
11533 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11534 return ReplaceInstUsesWith(IE, VecOp);
11535
11536 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11537 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11538
11539 // If we are extracting a value from a vector, then inserting it right
11540 // back into the same place, just use the input vector.
11541 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11542 return ReplaceInstUsesWith(IE, VecOp);
11543
11544 // We could theoretically do this for ANY input. However, doing so could
11545 // turn chains of insertelement instructions into a chain of shufflevector
11546 // instructions, and right now we do not merge shufflevectors. As such,
11547 // only do this in a situation where it is clear that there is benefit.
11548 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11549 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11550 // the values of VecOp, except then one read from EIOp0.
11551 // Build a new shuffle mask.
11552 std::vector<Constant*> Mask;
11553 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011554 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011555 else {
11556 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011557 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011558 NumVectorElts));
11559 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011560 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011561 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011562 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011563 }
11564
11565 // If this insertelement isn't used by some other insertelement, turn it
11566 // (and any insertelements it points to), into one big shuffle.
11567 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11568 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011569 Value *RHS = 0;
11570 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11571 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11572 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011573 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011574 }
11575 }
11576 }
11577
11578 return 0;
11579}
11580
11581
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011582Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11583 Value *LHS = SVI.getOperand(0);
11584 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011585 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011586
11587 bool MadeChange = false;
11588
Chris Lattner867b99f2006-10-05 06:55:50 +000011589 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011590 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011591 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11592
Chris Lattnere4929dd2007-01-05 07:36:08 +000011593 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011594 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011595 if (isa<UndefValue>(SVI.getOperand(1))) {
11596 // Scan to see if there are any references to the RHS. If so, replace them
11597 // with undef element refs and set MadeChange to true.
11598 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11599 if (Mask[i] >= e && Mask[i] != 2*e) {
11600 Mask[i] = 2*e;
11601 MadeChange = true;
11602 }
11603 }
11604
11605 if (MadeChange) {
11606 // Remap any references to RHS to use LHS.
11607 std::vector<Constant*> Elts;
11608 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11609 if (Mask[i] == 2*e)
11610 Elts.push_back(UndefValue::get(Type::Int32Ty));
11611 else
11612 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11613 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011614 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011615 }
11616 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011617
Chris Lattner863bcff2006-05-25 23:48:38 +000011618 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11619 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11620 if (LHS == RHS || isa<UndefValue>(LHS)) {
11621 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011622 // shuffle(undef,undef,mask) -> undef.
11623 return ReplaceInstUsesWith(SVI, LHS);
11624 }
11625
Chris Lattner863bcff2006-05-25 23:48:38 +000011626 // Remap any references to RHS to use LHS.
11627 std::vector<Constant*> Elts;
11628 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011629 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011630 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011631 else {
11632 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11633 (Mask[i] < e && isa<UndefValue>(LHS)))
11634 Mask[i] = 2*e; // Turn into undef.
11635 else
11636 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011637 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011638 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011639 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011640 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011641 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011642 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011643 LHS = SVI.getOperand(0);
11644 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011645 MadeChange = true;
11646 }
11647
Chris Lattner7b2e27922006-05-26 00:29:06 +000011648 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011649 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011650
Chris Lattner863bcff2006-05-25 23:48:38 +000011651 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11652 if (Mask[i] >= e*2) continue; // Ignore undef values.
11653 // Is this an identity shuffle of the LHS value?
11654 isLHSID &= (Mask[i] == i);
11655
11656 // Is this an identity shuffle of the RHS value?
11657 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011658 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011659
Chris Lattner863bcff2006-05-25 23:48:38 +000011660 // Eliminate identity shuffles.
11661 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11662 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011663
Chris Lattner7b2e27922006-05-26 00:29:06 +000011664 // If the LHS is a shufflevector itself, see if we can combine it with this
11665 // one without producing an unusual shuffle. Here we are really conservative:
11666 // we are absolutely afraid of producing a shuffle mask not in the input
11667 // program, because the code gen may not be smart enough to turn a merged
11668 // shuffle into two specific shuffles: it may produce worse code. As such,
11669 // we only merge two shuffles if the result is one of the two input shuffle
11670 // masks. In this case, merging the shuffles just removes one instruction,
11671 // which we know is safe. This is good for things like turning:
11672 // (splat(splat)) -> splat.
11673 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11674 if (isa<UndefValue>(RHS)) {
11675 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11676
11677 std::vector<unsigned> NewMask;
11678 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11679 if (Mask[i] >= 2*e)
11680 NewMask.push_back(2*e);
11681 else
11682 NewMask.push_back(LHSMask[Mask[i]]);
11683
11684 // If the result mask is equal to the src shuffle or this shuffle mask, do
11685 // the replacement.
11686 if (NewMask == LHSMask || NewMask == Mask) {
11687 std::vector<Constant*> Elts;
11688 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11689 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011690 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011691 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011692 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011693 }
11694 }
11695 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11696 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011697 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011698 }
11699 }
11700 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011701
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011702 return MadeChange ? &SVI : 0;
11703}
11704
11705
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011706
Chris Lattnerea1c4542004-12-08 23:43:58 +000011707
11708/// TryToSinkInstruction - Try to move the specified instruction from its
11709/// current block into the beginning of DestBlock, which can only happen if it's
11710/// safe to move the instruction past all of the instructions between it and the
11711/// end of its block.
11712static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11713 assert(I->hasOneUse() && "Invariants didn't hold!");
11714
Chris Lattner108e9022005-10-27 17:13:11 +000011715 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011716 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11717 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011718
Chris Lattnerea1c4542004-12-08 23:43:58 +000011719 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011720 if (isa<AllocaInst>(I) && I->getParent() ==
11721 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011722 return false;
11723
Chris Lattner96a52a62004-12-09 07:14:34 +000011724 // We can only sink load instructions if there is nothing between the load and
11725 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011726 if (I->mayReadFromMemory()) {
11727 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011728 Scan != E; ++Scan)
11729 if (Scan->mayWriteToMemory())
11730 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011731 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011732
11733 BasicBlock::iterator InsertPos = DestBlock->begin();
11734 while (isa<PHINode>(InsertPos)) ++InsertPos;
11735
Chris Lattner4bc5f802005-08-08 19:11:57 +000011736 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011737 ++NumSunkInst;
11738 return true;
11739}
11740
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011741
11742/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11743/// all reachable code to the worklist.
11744///
11745/// This has a couple of tricks to make the code faster and more powerful. In
11746/// particular, we constant fold and DCE instructions as we go, to avoid adding
11747/// them to the worklist (this significantly speeds up instcombine on code where
11748/// many instructions are dead or constant). Additionally, if we find a branch
11749/// whose condition is a known constant, we only visit the reachable successors.
11750///
11751static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011752 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011753 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011754 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011755 std::vector<BasicBlock*> Worklist;
11756 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011757
Chris Lattner2c7718a2007-03-23 19:17:18 +000011758 while (!Worklist.empty()) {
11759 BB = Worklist.back();
11760 Worklist.pop_back();
11761
11762 // We have now visited this block! If we've already been here, ignore it.
11763 if (!Visited.insert(BB)) continue;
11764
11765 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11766 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011767
Chris Lattner2c7718a2007-03-23 19:17:18 +000011768 // DCE instruction if trivially dead.
11769 if (isInstructionTriviallyDead(Inst)) {
11770 ++NumDeadInst;
11771 DOUT << "IC: DCE: " << *Inst;
11772 Inst->eraseFromParent();
11773 continue;
11774 }
11775
11776 // ConstantProp instruction if trivially constant.
11777 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11778 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11779 Inst->replaceAllUsesWith(C);
11780 ++NumConstProp;
11781 Inst->eraseFromParent();
11782 continue;
11783 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011784
Chris Lattner2c7718a2007-03-23 19:17:18 +000011785 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011786 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011787
11788 // Recursively visit successors. If this is a branch or switch on a
11789 // constant, only visit the reachable successor.
11790 TerminatorInst *TI = BB->getTerminator();
11791 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11792 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11793 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011794 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011795 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011796 continue;
11797 }
11798 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11799 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11800 // See if this is an explicit destination.
11801 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11802 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011803 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011804 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011805 continue;
11806 }
11807
11808 // Otherwise it is the default destination.
11809 Worklist.push_back(SI->getSuccessor(0));
11810 continue;
11811 }
11812 }
11813
11814 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11815 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011816 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011817}
11818
Chris Lattnerec9c3582007-03-03 02:04:50 +000011819bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011820 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011821 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011822
11823 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11824 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011825
Chris Lattnerb3d59702005-07-07 20:40:38 +000011826 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011827 // Do a depth-first traversal of the function, populate the worklist with
11828 // the reachable instructions. Ignore blocks that are not reachable. Keep
11829 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011830 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011831 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011832
Chris Lattnerb3d59702005-07-07 20:40:38 +000011833 // Do a quick scan over the function. If we find any blocks that are
11834 // unreachable, remove any instructions inside of them. This prevents
11835 // the instcombine code from having to deal with some bad special cases.
11836 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11837 if (!Visited.count(BB)) {
11838 Instruction *Term = BB->getTerminator();
11839 while (Term != BB->begin()) { // Remove instrs bottom-up
11840 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011841
Bill Wendlingb7427032006-11-26 09:46:52 +000011842 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011843 ++NumDeadInst;
11844
11845 if (!I->use_empty())
11846 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11847 I->eraseFromParent();
11848 }
11849 }
11850 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011851
Chris Lattnerdbab3862007-03-02 21:28:56 +000011852 while (!Worklist.empty()) {
11853 Instruction *I = RemoveOneFromWorkList();
11854 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011855
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011856 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011857 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011858 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011859 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011860 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011861 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011862
Bill Wendlingb7427032006-11-26 09:46:52 +000011863 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011864
11865 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011866 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011867 continue;
11868 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011869
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011870 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011871 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011872 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011873
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011874 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011875 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011876 ReplaceInstUsesWith(*I, C);
11877
Chris Lattner62b14df2002-09-02 04:59:56 +000011878 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011879 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011880 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011881 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011882 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011883
Chris Lattnerea1c4542004-12-08 23:43:58 +000011884 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011885 // FIXME: Remove GetResultInst test when first class support for aggregates
11886 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011887 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011888 BasicBlock *BB = I->getParent();
11889 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11890 if (UserParent != BB) {
11891 bool UserIsSuccessor = false;
11892 // See if the user is one of our successors.
11893 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11894 if (*SI == UserParent) {
11895 UserIsSuccessor = true;
11896 break;
11897 }
11898
11899 // If the user is one of our immediate successors, and if that successor
11900 // only has us as a predecessors (we'd have to split the critical edge
11901 // otherwise), we can keep going.
11902 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11903 next(pred_begin(UserParent)) == pred_end(UserParent))
11904 // Okay, the CFG is simple enough, try to sink this instruction.
11905 Changed |= TryToSinkInstruction(I, UserParent);
11906 }
11907 }
11908
Chris Lattner8a2a3112001-12-14 16:52:21 +000011909 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011910#ifndef NDEBUG
11911 std::string OrigI;
11912#endif
11913 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011914 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011915 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011916 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011917 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011918 DOUT << "IC: Old = " << *I
11919 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011920
Chris Lattnerf523d062004-06-09 05:08:07 +000011921 // Everything uses the new instruction now.
11922 I->replaceAllUsesWith(Result);
11923
11924 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011925 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011926 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011927
Chris Lattner6934a042007-02-11 01:23:03 +000011928 // Move the name to the new instruction first.
11929 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011930
11931 // Insert the new instruction into the basic block...
11932 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011933 BasicBlock::iterator InsertPos = I;
11934
11935 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11936 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11937 ++InsertPos;
11938
11939 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011940
Chris Lattner00d51312004-05-01 23:27:23 +000011941 // Make sure that we reprocess all operands now that we reduced their
11942 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011943 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011944
Chris Lattnerf523d062004-06-09 05:08:07 +000011945 // Instructions can end up on the worklist more than once. Make sure
11946 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011947 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011948
11949 // Erase the old instruction.
11950 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011951 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011952#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011953 DOUT << "IC: Mod = " << OrigI
11954 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011955#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011956
Chris Lattner90ac28c2002-08-02 19:29:35 +000011957 // If the instruction was modified, it's possible that it is now dead.
11958 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011959 if (isInstructionTriviallyDead(I)) {
11960 // Make sure we process all operands now that we are reducing their
11961 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011962 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011963
Chris Lattner00d51312004-05-01 23:27:23 +000011964 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011965 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011966 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011967 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011968 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011969 AddToWorkList(I);
11970 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011971 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011972 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011973 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011974 }
11975 }
11976
Chris Lattnerec9c3582007-03-03 02:04:50 +000011977 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011978
11979 // Do an explicit clear, this shrinks the map if needed.
11980 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011981 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011982}
11983
Chris Lattnerec9c3582007-03-03 02:04:50 +000011984
11985bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011986 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11987
Chris Lattnerec9c3582007-03-03 02:04:50 +000011988 bool EverMadeChange = false;
11989
11990 // Iterate while there is work to do.
11991 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011992 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011993 EverMadeChange = true;
11994 return EverMadeChange;
11995}
11996
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011997FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011998 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011999}
Brian Gaeked0fde302003-11-11 22:41:34 +000012000