blob: 74e6b6f6b060057627f6c7f8d1328f28ec4ae6d7 [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);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000553
554 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
555 if (C->getType()->getElementType()->isInteger())
556 return ConstantExpr::getNeg(C);
557
Chris Lattner8d969642003-03-10 23:06:50 +0000558 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000559}
560
Chris Lattner8d969642003-03-10 23:06:50 +0000561static inline Value *dyn_castNotVal(Value *V) {
562 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000563 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000564
565 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000566 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000567 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000568 return 0;
569}
570
Chris Lattnerc8802d22003-03-11 00:12:48 +0000571// dyn_castFoldableMul - If this value is a multiply that can be folded into
572// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000573// non-constant operand of the multiply, and set CST to point to the multiplier.
574// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000575//
Chris Lattner50af16a2004-11-13 19:50:12 +0000576static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000577 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000578 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000579 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000580 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000581 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000582 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000583 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000584 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000585 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000586 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000587 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000588 return I->getOperand(0);
589 }
590 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000592}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000593
Chris Lattner574da9b2005-01-13 20:14:25 +0000594/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
595/// expression, return it.
596static User *dyn_castGetElementPtr(Value *V) {
597 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
598 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
599 if (CE->getOpcode() == Instruction::GetElementPtr)
600 return cast<User>(V);
601 return false;
602}
603
Dan Gohmaneee962e2008-04-10 18:43:06 +0000604/// getOpcode - If this is an Instruction or a ConstantExpr, return the
605/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000606static unsigned getOpcode(const Value *V) {
607 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000608 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000609 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000610 return CE->getOpcode();
611 // Use UserOp1 to mean there's no opcode.
612 return Instruction::UserOp1;
613}
614
Reid Spencer7177c3a2007-03-25 05:33:51 +0000615/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000616static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000617 APInt Val(C->getValue());
618 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000619}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000620/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000621static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000622 APInt Val(C->getValue());
623 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000624}
625/// Add - Add two ConstantInts together
626static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
627 return ConstantInt::get(C1->getValue() + C2->getValue());
628}
629/// And - Bitwise AND two ConstantInts together
630static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
631 return ConstantInt::get(C1->getValue() & C2->getValue());
632}
633/// Subtract - Subtract one ConstantInt from another
634static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
635 return ConstantInt::get(C1->getValue() - C2->getValue());
636}
637/// Multiply - Multiply two ConstantInts together
638static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000640}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000641/// MultiplyOverflows - True if the multiply can not be expressed in an int
642/// this size.
643static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
644 uint32_t W = C1->getBitWidth();
645 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646 if (sign) {
647 LHSExt.sext(W * 2);
648 RHSExt.sext(W * 2);
649 } else {
650 LHSExt.zext(W * 2);
651 RHSExt.zext(W * 2);
652 }
653
654 APInt MulExt = LHSExt * RHSExt;
655
656 if (sign) {
657 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659 return MulExt.slt(Min) || MulExt.sgt(Max);
660 } else
661 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662}
Chris Lattner955f3312004-09-28 21:48:02 +0000663
Chris Lattner68d5ff22006-02-09 07:38:58 +0000664/// ComputeMaskedBits - Determine which of the bits specified in Mask are
665/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000666/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
667/// processing.
668/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
669/// we cannot optimize based on the assumption that it is zero without changing
670/// it to be an explicit zero. If we don't change it to zero, other code could
671/// optimized based on the contradictory assumption that it is non-zero.
672/// Because instcombine aggressively folds operations with undef args anyway,
673/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000674void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
675 APInt& KnownZero, APInt& KnownOne,
Dan Gohman45b4e482008-05-19 22:14:15 +0000676 unsigned Depth) const {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000677 assert(V && "No Value?");
678 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000679 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000680 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
681 "Not integer or pointer type!");
682 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
683 (!isa<IntegerType>(V->getType()) ||
684 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000685 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000686 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000687 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Dan Gohman45b4e482008-05-19 22:14:15 +0000688
Reid Spencer3e7594f2007-03-08 01:46:38 +0000689 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
690 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000691 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000692 KnownZero = ~KnownOne & Mask;
693 return;
694 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000695 // Null is all-zeros.
696 if (isa<ConstantPointerNull>(V)) {
697 KnownOne.clear();
698 KnownZero = Mask;
699 return;
700 }
701 // The address of an aligned GlobalValue has trailing zeros.
702 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
703 unsigned Align = GV->getAlignment();
704 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
705 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
706 if (Align > 0)
707 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
708 CountTrailingZeros_32(Align));
709 else
710 KnownZero.clear();
711 KnownOne.clear();
712 return;
713 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000714
Dan Gohman23e8b712008-04-28 17:02:21 +0000715 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
716
Reid Spencer3e7594f2007-03-08 01:46:38 +0000717 if (Depth == 6 || Mask == 0)
718 return; // Limit search depth.
719
Dan Gohmaneee962e2008-04-10 18:43:06 +0000720 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000721 if (!I) return;
722
723 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000724 switch (getOpcode(I)) {
725 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000726 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000727 // If either the LHS or the RHS are Zero, the result is zero.
728 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000729 APInt Mask2(Mask & ~KnownZero);
730 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000731 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
732 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
733
734 // Output known-1 bits are only known if set in both the LHS & RHS.
735 KnownOne &= KnownOne2;
736 // Output known-0 are known to be clear if zero in either the LHS | RHS.
737 KnownZero |= KnownZero2;
738 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000739 }
740 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000741 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000742 APInt Mask2(Mask & ~KnownOne);
743 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000744 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
745 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
746
747 // Output known-0 bits are only known if clear in both the LHS & RHS.
748 KnownZero &= KnownZero2;
749 // Output known-1 are known to be set if set in either the LHS | RHS.
750 KnownOne |= KnownOne2;
751 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000752 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000753 case Instruction::Xor: {
754 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
755 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
756 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
757 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
758
759 // Output known-0 bits are known if clear or set in both the LHS & RHS.
760 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
761 // Output known-1 are known to be set if set in only one of the LHS, RHS.
762 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
763 KnownZero = KnownZeroOut;
764 return;
765 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000766 case Instruction::Mul: {
767 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
768 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
769 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
770 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
771 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
772
773 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman23e8b712008-04-28 17:02:21 +0000774 // Also compute a conserative estimate for high known-0 bits.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000775 // More trickiness is possible, but this is sufficient for the
776 // interesting case of alignment computation.
777 KnownOne.clear();
778 unsigned TrailZ = KnownZero.countTrailingOnes() +
779 KnownZero2.countTrailingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +0000780 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman42ac9292008-05-07 00:35:55 +0000781 KnownZero2.countLeadingOnes(),
782 BitWidth) - BitWidth;
Dan Gohman23e8b712008-04-28 17:02:21 +0000783
Dan Gohmaneee962e2008-04-10 18:43:06 +0000784 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000785 LeadZ = std::min(LeadZ, BitWidth);
786 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
787 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000788 KnownZero &= Mask;
789 return;
790 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000791 case Instruction::UDiv: {
792 // For the purposes of computing leading zeros we can conservatively
793 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1d9cd502008-05-02 21:30:02 +0000794 // be less than the denominator.
Dan Gohman23e8b712008-04-28 17:02:21 +0000795 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
796 ComputeMaskedBits(I->getOperand(0),
797 AllOnes, KnownZero2, KnownOne2, Depth+1);
798 unsigned LeadZ = KnownZero2.countLeadingOnes();
799
800 KnownOne2.clear();
801 KnownZero2.clear();
802 ComputeMaskedBits(I->getOperand(1),
803 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1d9cd502008-05-02 21:30:02 +0000804 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
805 if (RHSUnknownLeadingOnes != BitWidth)
806 LeadZ = std::min(BitWidth,
807 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000808
809 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
810 return;
811 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000812 case Instruction::Select:
813 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
814 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
815 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
816 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
817
818 // Only known if known in both the LHS and RHS.
819 KnownOne &= KnownOne2;
820 KnownZero &= KnownZero2;
821 return;
822 case Instruction::FPTrunc:
823 case Instruction::FPExt:
824 case Instruction::FPToUI:
825 case Instruction::FPToSI:
826 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000827 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000828 return; // Can't work with floating point.
829 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000830 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000831 // We can't handle these if we don't know the pointer size.
832 if (!TD) return;
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000833 // FALL THROUGH and handle them the same as zext/trunc.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000834 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000835 case Instruction::Trunc: {
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000836 // Note that we handle pointer operands here because of inttoptr/ptrtoint
837 // which fall through here.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000838 const Type *SrcTy = I->getOperand(0)->getType();
839 uint32_t SrcBitWidth = TD ?
840 TD->getTypeSizeInBits(SrcTy) :
841 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000842 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000843 MaskIn.zextOrTrunc(SrcBitWidth);
844 KnownZero.zextOrTrunc(SrcBitWidth);
845 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000846 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000847 KnownZero.zextOrTrunc(BitWidth);
848 KnownOne.zextOrTrunc(BitWidth);
849 // Any top bits are known to be zero.
850 if (BitWidth > SrcBitWidth)
851 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000852 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000853 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000854 case Instruction::BitCast: {
855 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000856 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000857 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
858 return;
859 }
860 break;
861 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000862 case Instruction::SExt: {
863 // Compute the bits in the result that are not present in the input.
864 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000865 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000866
Zhou Shengaa305ab2007-03-28 02:19:03 +0000867 APInt MaskIn(Mask);
868 MaskIn.trunc(SrcBitWidth);
869 KnownZero.trunc(SrcBitWidth);
870 KnownOne.trunc(SrcBitWidth);
871 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000872 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000873 KnownZero.zext(BitWidth);
874 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000875
876 // If the sign bit of the input is known set or clear, then we know the
877 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000878 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000879 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000880 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000881 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000882 return;
883 }
884 case Instruction::Shl:
885 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
886 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000887 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000888 APInt Mask2(Mask.lshr(ShiftAmt));
889 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000890 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000891 KnownZero <<= ShiftAmt;
892 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000893 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000894 return;
895 }
896 break;
897 case Instruction::LShr:
898 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
899 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
900 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000901 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000902
903 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000904 APInt Mask2(Mask.shl(ShiftAmt));
905 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000906 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
907 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
908 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000909 // high bits known zero.
910 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000911 return;
912 }
913 break;
914 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000915 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000916 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
917 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000918 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000919
920 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000921 APInt Mask2(Mask.shl(ShiftAmt));
922 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000923 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
924 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
925 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
926
Zhou Shengaa305ab2007-03-28 02:19:03 +0000927 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
928 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000929 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000930 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000931 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000932 return;
933 }
934 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000935 case Instruction::Sub: {
936 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
937 // We know that the top bits of C-X are clear if X contains less bits
938 // than C (i.e. no wrap-around can happen). For example, 20-X is
939 // positive if we can prove that X is >= 0 and < 16.
940 if (!CLHS->getValue().isNegative()) {
941 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
942 // NLZ can't be BitWidth with no sign bit
943 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000944 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
945 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000946
Dan Gohman23e8b712008-04-28 17:02:21 +0000947 // If all of the MaskV bits are known to be zero, then we know the
948 // output top bits are zero, because we now know that the output is
949 // from [0-C].
950 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000951 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
952 // Top bits known zero.
953 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000954 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000955 }
956 }
957 }
958 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000959 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000960 // Output known-0 bits are known if clear or set in both the low clear bits
961 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
962 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000963 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
964 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
965 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
966 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
967
968 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
969 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
970 KnownZeroOut = std::min(KnownZeroOut,
971 KnownZero2.countTrailingOnes());
972
973 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000974 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000975 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000976 case Instruction::SRem:
977 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
978 APInt RA = Rem->getValue();
979 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000980 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000981 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
982 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
983
984 // The sign of a remainder is equal to the sign of the first
985 // operand (zero being positive).
986 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
987 KnownZero2 |= ~LowBits;
988 else if (KnownOne2[BitWidth-1])
989 KnownOne2 |= ~LowBits;
990
991 KnownZero |= KnownZero2 & Mask;
992 KnownOne |= KnownOne2 & Mask;
993
994 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
995 }
996 }
997 break;
Dan Gohman23e8b712008-04-28 17:02:21 +0000998 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000999 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1000 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001001 if (RA.isPowerOf2()) {
1002 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001003 APInt Mask2 = LowBits & Mask;
1004 KnownZero |= ~LowBits & Mask;
1005 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1006 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001007 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001008 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001009 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001010
1011 // Since the result is less than or equal to either operand, any leading
1012 // zero bits in either operand must also exist in the result.
1013 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1014 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1015 Depth+1);
1016 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1017 Depth+1);
1018
1019 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1020 KnownZero2.countLeadingOnes());
1021 KnownOne.clear();
1022 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001023 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001024 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001025
1026 case Instruction::Alloca:
1027 case Instruction::Malloc: {
1028 AllocationInst *AI = cast<AllocationInst>(V);
1029 unsigned Align = AI->getAlignment();
1030 if (Align == 0 && TD) {
1031 if (isa<AllocaInst>(AI))
1032 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1033 else if (isa<MallocInst>(AI)) {
1034 // Malloc returns maximally aligned memory.
1035 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1036 Align =
1037 std::max(Align,
1038 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1039 Align =
1040 std::max(Align,
1041 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1042 }
1043 }
1044
1045 if (Align > 0)
1046 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1047 CountTrailingZeros_32(Align));
1048 break;
1049 }
1050 case Instruction::GetElementPtr: {
1051 // Analyze all of the subscripts of this getelementptr instruction
1052 // to determine if we can prove known low zero bits.
1053 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1054 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1055 ComputeMaskedBits(I->getOperand(0), LocalMask,
1056 LocalKnownZero, LocalKnownOne, Depth+1);
1057 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1058
1059 gep_type_iterator GTI = gep_type_begin(I);
1060 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1061 Value *Index = I->getOperand(i);
1062 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1063 // Handle struct member offset arithmetic.
1064 if (!TD) return;
1065 const StructLayout *SL = TD->getStructLayout(STy);
1066 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1067 uint64_t Offset = SL->getElementOffset(Idx);
1068 TrailZ = std::min(TrailZ,
1069 CountTrailingZeros_64(Offset));
1070 } else {
1071 // Handle array index arithmetic.
1072 const Type *IndexedTy = GTI.getIndexedType();
1073 if (!IndexedTy->isSized()) return;
1074 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1075 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1076 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1077 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1078 ComputeMaskedBits(Index, LocalMask,
1079 LocalKnownZero, LocalKnownOne, Depth+1);
1080 TrailZ = std::min(TrailZ,
1081 CountTrailingZeros_64(TypeSize) +
1082 LocalKnownZero.countTrailingOnes());
1083 }
1084 }
1085
1086 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1087 break;
1088 }
1089 case Instruction::PHI: {
1090 PHINode *P = cast<PHINode>(I);
1091 // Handle the case of a simple two-predecessor recurrence PHI.
1092 // There's a lot more that could theoretically be done here, but
1093 // this is sufficient to catch some interesting cases.
1094 if (P->getNumIncomingValues() == 2) {
1095 for (unsigned i = 0; i != 2; ++i) {
1096 Value *L = P->getIncomingValue(i);
1097 Value *R = P->getIncomingValue(!i);
1098 User *LU = dyn_cast<User>(L);
Matthijs Kooijman214142c2008-05-23 16:17:48 +00001099 if (!LU)
1100 continue;
1101 unsigned Opcode = getOpcode(LU);
Dan Gohmaneee962e2008-04-10 18:43:06 +00001102 // Check for operations that have the property that if
1103 // both their operands have low zero bits, the result
1104 // will have low zero bits.
1105 if (Opcode == Instruction::Add ||
1106 Opcode == Instruction::Sub ||
1107 Opcode == Instruction::And ||
1108 Opcode == Instruction::Or ||
1109 Opcode == Instruction::Mul) {
1110 Value *LL = LU->getOperand(0);
1111 Value *LR = LU->getOperand(1);
1112 // Find a recurrence.
1113 if (LL == I)
1114 L = LR;
1115 else if (LR == I)
1116 L = LL;
1117 else
1118 break;
1119 // Ok, we have a PHI of the form L op= R. Check for low
1120 // zero bits.
1121 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1122 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1123 Mask2 = APInt::getLowBitsSet(BitWidth,
1124 KnownZero2.countTrailingOnes());
1125 KnownOne2.clear();
1126 KnownZero2.clear();
1127 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1128 KnownZero = Mask &
1129 APInt::getLowBitsSet(BitWidth,
1130 KnownZero2.countTrailingOnes());
1131 break;
1132 }
1133 }
1134 }
1135 break;
1136 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001137 case Instruction::Call:
1138 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1139 switch (II->getIntrinsicID()) {
1140 default: break;
1141 case Intrinsic::ctpop:
1142 case Intrinsic::ctlz:
1143 case Intrinsic::cttz: {
1144 unsigned LowBits = Log2_32(BitWidth)+1;
1145 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1146 break;
1147 }
1148 }
1149 }
1150 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001151 }
1152}
1153
Reid Spencere7816b52007-03-08 01:52:58 +00001154/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1155/// this predicate to simplify operations downstream. Mask is known to be zero
1156/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001157bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1158 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001159 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001160 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1161 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1162 return (KnownZero & Mask) == Mask;
1163}
1164
Chris Lattner255d8912006-02-11 09:31:47 +00001165/// ShrinkDemandedConstant - Check to see if the specified operand of the
1166/// specified instruction is a constant integer. If so, check to see if there
1167/// are any bits set in the constant that are not demanded. If so, shrink the
1168/// constant and return true.
1169static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001170 APInt Demanded) {
1171 assert(I && "No instruction?");
1172 assert(OpNo < I->getNumOperands() && "Operand index too large");
1173
1174 // If the operand is not a constant integer, nothing to do.
1175 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1176 if (!OpC) return false;
1177
1178 // If there are no bits set that aren't demanded, nothing to do.
1179 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1180 if ((~Demanded & OpC->getValue()) == 0)
1181 return false;
1182
1183 // This instruction is producing bits that are not demanded. Shrink the RHS.
1184 Demanded &= OpC->getValue();
1185 I->setOperand(OpNo, ConstantInt::get(Demanded));
1186 return true;
1187}
1188
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001189// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1190// set of known zero and one bits, compute the maximum and minimum values that
1191// could have the specified known zero and known one bits, returning them in
1192// min/max.
1193static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001194 const APInt& KnownZero,
1195 const APInt& KnownOne,
1196 APInt& Min, APInt& Max) {
1197 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1198 assert(KnownZero.getBitWidth() == BitWidth &&
1199 KnownOne.getBitWidth() == BitWidth &&
1200 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1201 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001202 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001203
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001204 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1205 // bit if it is unknown.
1206 Min = KnownOne;
1207 Max = KnownOne|UnknownBits;
1208
Zhou Sheng4acf1552007-03-28 05:15:57 +00001209 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001210 Min.set(BitWidth-1);
1211 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001212 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001213}
1214
1215// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1216// a set of known zero and one bits, compute the maximum and minimum values that
1217// could have the specified known zero and known one bits, returning them in
1218// min/max.
1219static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001220 const APInt &KnownZero,
1221 const APInt &KnownOne,
1222 APInt &Min, APInt &Max) {
1223 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001224 assert(KnownZero.getBitWidth() == BitWidth &&
1225 KnownOne.getBitWidth() == BitWidth &&
1226 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1227 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001228 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001229
1230 // The minimum value is when the unknown bits are all zeros.
1231 Min = KnownOne;
1232 // The maximum value is when the unknown bits are all ones.
1233 Max = KnownOne|UnknownBits;
1234}
Chris Lattner255d8912006-02-11 09:31:47 +00001235
Reid Spencer8cb68342007-03-12 17:25:59 +00001236/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1237/// value based on the demanded bits. When this function is called, it is known
1238/// that only the bits set in DemandedMask of the result of V are ever used
1239/// downstream. Consequently, depending on the mask and V, it may be possible
1240/// to replace V with a constant or one of its operands. In such cases, this
1241/// function does the replacement and returns true. In all other cases, it
1242/// returns false after analyzing the expression and setting KnownOne and known
1243/// to be one in the expression. KnownZero contains all the bits that are known
1244/// to be zero in the expression. These are provided to potentially allow the
1245/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1246/// the expression. KnownOne and KnownZero always follow the invariant that
1247/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1248/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1249/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1250/// and KnownOne must all be the same.
1251bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1252 APInt& KnownZero, APInt& KnownOne,
1253 unsigned Depth) {
1254 assert(V != 0 && "Null pointer of Value???");
1255 assert(Depth <= 6 && "Limit Search Depth");
1256 uint32_t BitWidth = DemandedMask.getBitWidth();
1257 const IntegerType *VTy = cast<IntegerType>(V->getType());
1258 assert(VTy->getBitWidth() == BitWidth &&
1259 KnownZero.getBitWidth() == BitWidth &&
1260 KnownOne.getBitWidth() == BitWidth &&
1261 "Value *V, DemandedMask, KnownZero and KnownOne \
1262 must have same BitWidth");
1263 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1264 // We know all of the bits for a constant!
1265 KnownOne = CI->getValue() & DemandedMask;
1266 KnownZero = ~KnownOne & DemandedMask;
1267 return false;
1268 }
1269
Zhou Sheng96704452007-03-14 03:21:24 +00001270 KnownZero.clear();
1271 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001272 if (!V->hasOneUse()) { // Other users may use these bits.
1273 if (Depth != 0) { // Not at the root.
1274 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1275 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1276 return false;
1277 }
1278 // If this is the root being simplified, allow it to have multiple uses,
1279 // just set the DemandedMask to all bits.
1280 DemandedMask = APInt::getAllOnesValue(BitWidth);
1281 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1282 if (V != UndefValue::get(VTy))
1283 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1284 return false;
1285 } else if (Depth == 6) { // Limit search depth.
1286 return false;
1287 }
1288
1289 Instruction *I = dyn_cast<Instruction>(V);
1290 if (!I) return false; // Only analyze instructions.
1291
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1293 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1294 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001295 default:
1296 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1297 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 case Instruction::And:
1299 // If either the LHS or the RHS are Zero, the result is zero.
1300 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1301 RHSKnownZero, RHSKnownOne, Depth+1))
1302 return true;
1303 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1304 "Bits known to be one AND zero?");
1305
1306 // If something is known zero on the RHS, the bits aren't demanded on the
1307 // LHS.
1308 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1309 LHSKnownZero, LHSKnownOne, Depth+1))
1310 return true;
1311 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1312 "Bits known to be one AND zero?");
1313
1314 // If all of the demanded bits are known 1 on one side, return the other.
1315 // These bits cannot contribute to the result of the 'and'.
1316 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1317 (DemandedMask & ~LHSKnownZero))
1318 return UpdateValueUsesWith(I, I->getOperand(0));
1319 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1320 (DemandedMask & ~RHSKnownZero))
1321 return UpdateValueUsesWith(I, I->getOperand(1));
1322
1323 // If all of the demanded bits in the inputs are known zeros, return zero.
1324 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1325 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1326
1327 // If the RHS is a constant, see if we can simplify it.
1328 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1329 return UpdateValueUsesWith(I, I);
1330
1331 // Output known-1 bits are only known if set in both the LHS & RHS.
1332 RHSKnownOne &= LHSKnownOne;
1333 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1334 RHSKnownZero |= LHSKnownZero;
1335 break;
1336 case Instruction::Or:
1337 // If either the LHS or the RHS are One, the result is One.
1338 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1339 RHSKnownZero, RHSKnownOne, Depth+1))
1340 return true;
1341 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1342 "Bits known to be one AND zero?");
1343 // If something is known one on the RHS, the bits aren't demanded on the
1344 // LHS.
1345 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1346 LHSKnownZero, LHSKnownOne, Depth+1))
1347 return true;
1348 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1349 "Bits known to be one AND zero?");
1350
1351 // If all of the demanded bits are known zero on one side, return the other.
1352 // These bits cannot contribute to the result of the 'or'.
1353 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1354 (DemandedMask & ~LHSKnownOne))
1355 return UpdateValueUsesWith(I, I->getOperand(0));
1356 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1357 (DemandedMask & ~RHSKnownOne))
1358 return UpdateValueUsesWith(I, I->getOperand(1));
1359
1360 // If all of the potentially set bits on one side are known to be set on
1361 // the other side, just use the 'other' side.
1362 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1363 (DemandedMask & (~RHSKnownZero)))
1364 return UpdateValueUsesWith(I, I->getOperand(0));
1365 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1366 (DemandedMask & (~LHSKnownZero)))
1367 return UpdateValueUsesWith(I, I->getOperand(1));
1368
1369 // If the RHS is a constant, see if we can simplify it.
1370 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1371 return UpdateValueUsesWith(I, I);
1372
1373 // Output known-0 bits are only known if clear in both the LHS & RHS.
1374 RHSKnownZero &= LHSKnownZero;
1375 // Output known-1 are known to be set if set in either the LHS | RHS.
1376 RHSKnownOne |= LHSKnownOne;
1377 break;
1378 case Instruction::Xor: {
1379 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1380 RHSKnownZero, RHSKnownOne, Depth+1))
1381 return true;
1382 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1383 "Bits known to be one AND zero?");
1384 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1385 LHSKnownZero, LHSKnownOne, Depth+1))
1386 return true;
1387 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1388 "Bits known to be one AND zero?");
1389
1390 // If all of the demanded bits are known zero on one side, return the other.
1391 // These bits cannot contribute to the result of the 'xor'.
1392 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1393 return UpdateValueUsesWith(I, I->getOperand(0));
1394 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1395 return UpdateValueUsesWith(I, I->getOperand(1));
1396
1397 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1398 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1399 (RHSKnownOne & LHSKnownOne);
1400 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1401 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1402 (RHSKnownOne & LHSKnownZero);
1403
1404 // If all of the demanded bits are known to be zero on one side or the
1405 // other, turn this into an *inclusive* or.
1406 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1407 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1408 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001409 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001410 I->getName());
1411 InsertNewInstBefore(Or, *I);
1412 return UpdateValueUsesWith(I, Or);
1413 }
1414
1415 // If all of the demanded bits on one side are known, and all of the set
1416 // bits on that side are also known to be set on the other side, turn this
1417 // into an AND, as we know the bits will be cleared.
1418 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1419 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1420 // all known
1421 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1422 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1423 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001424 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +00001425 InsertNewInstBefore(And, *I);
1426 return UpdateValueUsesWith(I, And);
1427 }
1428 }
1429
1430 // If the RHS is a constant, see if we can simplify it.
1431 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1432 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1433 return UpdateValueUsesWith(I, I);
1434
1435 RHSKnownZero = KnownZeroOut;
1436 RHSKnownOne = KnownOneOut;
1437 break;
1438 }
1439 case Instruction::Select:
1440 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1441 RHSKnownZero, RHSKnownOne, Depth+1))
1442 return true;
1443 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1444 LHSKnownZero, LHSKnownOne, Depth+1))
1445 return true;
1446 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1447 "Bits known to be one AND zero?");
1448 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1449 "Bits known to be one AND zero?");
1450
1451 // If the operands are constants, see if we can simplify them.
1452 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1453 return UpdateValueUsesWith(I, I);
1454 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1455 return UpdateValueUsesWith(I, I);
1456
1457 // Only known if known in both the LHS and RHS.
1458 RHSKnownOne &= LHSKnownOne;
1459 RHSKnownZero &= LHSKnownZero;
1460 break;
1461 case Instruction::Trunc: {
1462 uint32_t truncBf =
1463 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001464 DemandedMask.zext(truncBf);
1465 RHSKnownZero.zext(truncBf);
1466 RHSKnownOne.zext(truncBf);
1467 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1468 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001469 return true;
1470 DemandedMask.trunc(BitWidth);
1471 RHSKnownZero.trunc(BitWidth);
1472 RHSKnownOne.trunc(BitWidth);
1473 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1474 "Bits known to be one AND zero?");
1475 break;
1476 }
1477 case Instruction::BitCast:
1478 if (!I->getOperand(0)->getType()->isInteger())
1479 return false;
1480
1481 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1482 RHSKnownZero, RHSKnownOne, Depth+1))
1483 return true;
1484 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1485 "Bits known to be one AND zero?");
1486 break;
1487 case Instruction::ZExt: {
1488 // Compute the bits in the result that are not present in the input.
1489 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001490 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001491
Zhou Shengd48653a2007-03-29 04:45:55 +00001492 DemandedMask.trunc(SrcBitWidth);
1493 RHSKnownZero.trunc(SrcBitWidth);
1494 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001495 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1496 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001497 return true;
1498 DemandedMask.zext(BitWidth);
1499 RHSKnownZero.zext(BitWidth);
1500 RHSKnownOne.zext(BitWidth);
1501 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1502 "Bits known to be one AND zero?");
1503 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001504 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001505 break;
1506 }
1507 case Instruction::SExt: {
1508 // Compute the bits in the result that are not present in the input.
1509 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001510 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001511
Reid Spencer8cb68342007-03-12 17:25:59 +00001512 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001513 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001514
Zhou Sheng01542f32007-03-29 02:26:30 +00001515 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001516 // If any of the sign extended bits are demanded, we know that the sign
1517 // bit is demanded.
1518 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001519 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001520
Zhou Shengd48653a2007-03-29 04:45:55 +00001521 InputDemandedBits.trunc(SrcBitWidth);
1522 RHSKnownZero.trunc(SrcBitWidth);
1523 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001524 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1525 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001526 return true;
1527 InputDemandedBits.zext(BitWidth);
1528 RHSKnownZero.zext(BitWidth);
1529 RHSKnownOne.zext(BitWidth);
1530 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1531 "Bits known to be one AND zero?");
1532
1533 // If the sign bit of the input is known set or clear, then we know the
1534 // top bits of the result.
1535
1536 // If the input sign bit is known zero, or if the NewBits are not demanded
1537 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001538 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001539 {
1540 // Convert to ZExt cast
1541 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1542 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001543 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001544 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001545 }
1546 break;
1547 }
1548 case Instruction::Add: {
1549 // Figure out what the input bits are. If the top bits of the and result
1550 // are not demanded, then the add doesn't demand them from its input
1551 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001552 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001553
1554 // If there is a constant on the RHS, there are a variety of xformations
1555 // we can do.
1556 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1557 // If null, this should be simplified elsewhere. Some of the xforms here
1558 // won't work if the RHS is zero.
1559 if (RHS->isZero())
1560 break;
1561
1562 // If the top bit of the output is demanded, demand everything from the
1563 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001564 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001565
1566 // Find information about known zero/one bits in the input.
1567 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1568 LHSKnownZero, LHSKnownOne, Depth+1))
1569 return true;
1570
1571 // If the RHS of the add has bits set that can't affect the input, reduce
1572 // the constant.
1573 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1574 return UpdateValueUsesWith(I, I);
1575
1576 // Avoid excess work.
1577 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1578 break;
1579
1580 // Turn it into OR if input bits are zero.
1581 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1582 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001583 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001584 I->getName());
1585 InsertNewInstBefore(Or, *I);
1586 return UpdateValueUsesWith(I, Or);
1587 }
1588
1589 // We can say something about the output known-zero and known-one bits,
1590 // depending on potential carries from the input constant and the
1591 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1592 // bits set and the RHS constant is 0x01001, then we know we have a known
1593 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1594
1595 // To compute this, we first compute the potential carry bits. These are
1596 // the bits which may be modified. I'm not aware of a better way to do
1597 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001598 const APInt& RHSVal = RHS->getValue();
1599 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001600
1601 // Now that we know which bits have carries, compute the known-1/0 sets.
1602
1603 // Bits are known one if they are known zero in one operand and one in the
1604 // other, and there is no input carry.
1605 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1606 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1607
1608 // Bits are known zero if they are known zero in both operands and there
1609 // is no input carry.
1610 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1611 } else {
1612 // If the high-bits of this ADD are not demanded, then it does not demand
1613 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001614 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001615 // Right fill the mask of bits for this ADD to demand the most
1616 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001617 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001618 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1619 LHSKnownZero, LHSKnownOne, Depth+1))
1620 return true;
1621 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1622 LHSKnownZero, LHSKnownOne, Depth+1))
1623 return true;
1624 }
1625 }
1626 break;
1627 }
1628 case Instruction::Sub:
1629 // If the high-bits of this SUB are not demanded, then it does not demand
1630 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001631 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001632 // Right fill the mask of bits for this SUB to demand the most
1633 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001634 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001635 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001636 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1637 LHSKnownZero, LHSKnownOne, Depth+1))
1638 return true;
1639 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1640 LHSKnownZero, LHSKnownOne, Depth+1))
1641 return true;
1642 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001643 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1644 // the known zeros and ones.
1645 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001646 break;
1647 case Instruction::Shl:
1648 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001649 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001650 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1651 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001652 RHSKnownZero, RHSKnownOne, Depth+1))
1653 return true;
1654 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1655 "Bits known to be one AND zero?");
1656 RHSKnownZero <<= ShiftAmt;
1657 RHSKnownOne <<= ShiftAmt;
1658 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001659 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001660 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001661 }
1662 break;
1663 case Instruction::LShr:
1664 // For a logical shift right
1665 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001666 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001667
Reid Spencer8cb68342007-03-12 17:25:59 +00001668 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001669 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1670 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001671 RHSKnownZero, RHSKnownOne, Depth+1))
1672 return true;
1673 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1674 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001675 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1676 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001677 if (ShiftAmt) {
1678 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001679 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001680 RHSKnownZero |= HighBits; // high bits known zero.
1681 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001682 }
1683 break;
1684 case Instruction::AShr:
1685 // If this is an arithmetic shift right and only the low-bit is set, we can
1686 // always convert this into a logical shr, even if the shift amount is
1687 // variable. The low bit of the shift cannot be an input sign bit unless
1688 // the shift amount is >= the size of the datatype, which is undefined.
1689 if (DemandedMask == 1) {
1690 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001691 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001692 I->getOperand(0), I->getOperand(1), I->getName());
1693 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1694 return UpdateValueUsesWith(I, NewVal);
1695 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001696
1697 // If the sign bit is the only bit demanded by this ashr, then there is no
1698 // need to do it, the shift doesn't change the high bit.
1699 if (DemandedMask.isSignBit())
1700 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001701
1702 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001703 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001704
Reid Spencer8cb68342007-03-12 17:25:59 +00001705 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001706 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001707 // If any of the "high bits" are demanded, we should set the sign bit as
1708 // demanded.
1709 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1710 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001711 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001712 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001713 RHSKnownZero, RHSKnownOne, Depth+1))
1714 return true;
1715 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1716 "Bits known to be one AND zero?");
1717 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001718 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001719 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1720 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1721
1722 // Handle the sign bits.
1723 APInt SignBit(APInt::getSignBit(BitWidth));
1724 // Adjust to where it is now in the mask.
1725 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1726
1727 // If the input sign bit is known to be zero, or if none of the top bits
1728 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001729 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001730 (HighBits & ~DemandedMask) == HighBits) {
1731 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001732 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001733 I->getOperand(0), SA, I->getName());
1734 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1735 return UpdateValueUsesWith(I, NewVal);
1736 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1737 RHSKnownOne |= HighBits;
1738 }
1739 }
1740 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001741 case Instruction::SRem:
1742 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1743 APInt RA = Rem->getValue();
1744 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001745 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001746 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1747 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1748 LHSKnownZero, LHSKnownOne, Depth+1))
1749 return true;
1750
1751 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1752 LHSKnownZero |= ~LowBits;
1753 else if (LHSKnownOne[BitWidth-1])
1754 LHSKnownOne |= ~LowBits;
1755
1756 KnownZero |= LHSKnownZero & DemandedMask;
1757 KnownOne |= LHSKnownOne & DemandedMask;
1758
1759 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1760 }
1761 }
1762 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001763 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001764 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1765 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001766 if (RA.isPowerOf2()) {
1767 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001768 APInt Mask2 = LowBits & DemandedMask;
1769 KnownZero |= ~LowBits & DemandedMask;
1770 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1771 KnownZero, KnownOne, Depth+1))
1772 return true;
1773
1774 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001775 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001776 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001777 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001778
1779 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1780 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001781 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1782 KnownZero2, KnownOne2, Depth+1))
1783 return true;
1784
Dan Gohman23e8b712008-04-28 17:02:21 +00001785 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001786 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001787 KnownZero2, KnownOne2, Depth+1))
1788 return true;
1789
1790 Leaders = std::max(Leaders,
1791 KnownZero2.countLeadingOnes());
1792 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001793 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001794 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001795 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001796
1797 // If the client is only demanding bits that we know, return the known
1798 // constant.
1799 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1800 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1801 return false;
1802}
1803
Chris Lattner867b99f2006-10-05 06:55:50 +00001804
1805/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1806/// 64 or fewer elements. DemandedElts contains the set of elements that are
1807/// actually used by the caller. This method analyzes which elements of the
1808/// operand are undef and returns that information in UndefElts.
1809///
1810/// If the information about demanded elements can be used to simplify the
1811/// operation, the operation is simplified, then the resultant value is
1812/// returned. This returns null if no change was made.
1813Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1814 uint64_t &UndefElts,
1815 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001816 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001817 assert(VWidth <= 64 && "Vector too wide to analyze!");
1818 uint64_t EltMask = ~0ULL >> (64-VWidth);
1819 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1820 "Invalid DemandedElts!");
1821
1822 if (isa<UndefValue>(V)) {
1823 // If the entire vector is undefined, just return this info.
1824 UndefElts = EltMask;
1825 return 0;
1826 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1827 UndefElts = EltMask;
1828 return UndefValue::get(V->getType());
1829 }
1830
1831 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001832 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1833 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001834 Constant *Undef = UndefValue::get(EltTy);
1835
1836 std::vector<Constant*> Elts;
1837 for (unsigned i = 0; i != VWidth; ++i)
1838 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1839 Elts.push_back(Undef);
1840 UndefElts |= (1ULL << i);
1841 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1842 Elts.push_back(Undef);
1843 UndefElts |= (1ULL << i);
1844 } else { // Otherwise, defined.
1845 Elts.push_back(CP->getOperand(i));
1846 }
1847
1848 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001849 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001850 return NewCP != CP ? NewCP : 0;
1851 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001852 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001853 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001854 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001855 Constant *Zero = Constant::getNullValue(EltTy);
1856 Constant *Undef = UndefValue::get(EltTy);
1857 std::vector<Constant*> Elts;
1858 for (unsigned i = 0; i != VWidth; ++i)
1859 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1860 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001861 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001862 }
1863
1864 if (!V->hasOneUse()) { // Other users may use these bits.
1865 if (Depth != 0) { // Not at the root.
1866 // TODO: Just compute the UndefElts information recursively.
1867 return false;
1868 }
1869 return false;
1870 } else if (Depth == 10) { // Limit search depth.
1871 return false;
1872 }
1873
1874 Instruction *I = dyn_cast<Instruction>(V);
1875 if (!I) return false; // Only analyze instructions.
1876
1877 bool MadeChange = false;
1878 uint64_t UndefElts2;
1879 Value *TmpV;
1880 switch (I->getOpcode()) {
1881 default: break;
1882
1883 case Instruction::InsertElement: {
1884 // If this is a variable index, we don't know which element it overwrites.
1885 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001886 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001887 if (Idx == 0) {
1888 // Note that we can't propagate undef elt info, because we don't know
1889 // which elt is getting updated.
1890 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1891 UndefElts2, Depth+1);
1892 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1893 break;
1894 }
1895
1896 // If this is inserting an element that isn't demanded, remove this
1897 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001898 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001899 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1900 return AddSoonDeadInstToWorklist(*I, 0);
1901
1902 // Otherwise, the element inserted overwrites whatever was there, so the
1903 // input demanded set is simpler than the output set.
1904 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1905 DemandedElts & ~(1ULL << IdxNo),
1906 UndefElts, Depth+1);
1907 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1908
1909 // The inserted element is defined.
1910 UndefElts |= 1ULL << IdxNo;
1911 break;
1912 }
Chris Lattner69878332007-04-14 22:29:23 +00001913 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001914 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001915 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1916 if (!VTy) break;
1917 unsigned InVWidth = VTy->getNumElements();
1918 uint64_t InputDemandedElts = 0;
1919 unsigned Ratio;
1920
1921 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001922 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001923 // elements as are demanded of us.
1924 Ratio = 1;
1925 InputDemandedElts = DemandedElts;
1926 } else if (VWidth > InVWidth) {
1927 // Untested so far.
1928 break;
1929
1930 // If there are more elements in the result than there are in the source,
1931 // then an input element is live if any of the corresponding output
1932 // elements are live.
1933 Ratio = VWidth/InVWidth;
1934 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1935 if (DemandedElts & (1ULL << OutIdx))
1936 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1937 }
1938 } else {
1939 // Untested so far.
1940 break;
1941
1942 // If there are more elements in the source than there are in the result,
1943 // then an input element is live if the corresponding output element is
1944 // live.
1945 Ratio = InVWidth/VWidth;
1946 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1947 if (DemandedElts & (1ULL << InIdx/Ratio))
1948 InputDemandedElts |= 1ULL << InIdx;
1949 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001950
Chris Lattner69878332007-04-14 22:29:23 +00001951 // div/rem demand all inputs, because they don't want divide by zero.
1952 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1953 UndefElts2, Depth+1);
1954 if (TmpV) {
1955 I->setOperand(0, TmpV);
1956 MadeChange = true;
1957 }
1958
1959 UndefElts = UndefElts2;
1960 if (VWidth > InVWidth) {
1961 assert(0 && "Unimp");
1962 // If there are more elements in the result than there are in the source,
1963 // then an output element is undef if the corresponding input element is
1964 // undef.
1965 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1966 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1967 UndefElts |= 1ULL << OutIdx;
1968 } else if (VWidth < InVWidth) {
1969 assert(0 && "Unimp");
1970 // If there are more elements in the source than there are in the result,
1971 // then a result element is undef if all of the corresponding input
1972 // elements are undef.
1973 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1974 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1975 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1976 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1977 }
1978 break;
1979 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001980 case Instruction::And:
1981 case Instruction::Or:
1982 case Instruction::Xor:
1983 case Instruction::Add:
1984 case Instruction::Sub:
1985 case Instruction::Mul:
1986 // div/rem demand all inputs, because they don't want divide by zero.
1987 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1988 UndefElts, Depth+1);
1989 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1990 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1991 UndefElts2, Depth+1);
1992 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1993
1994 // Output elements are undefined if both are undefined. Consider things
1995 // like undef&0. The result is known zero, not undef.
1996 UndefElts &= UndefElts2;
1997 break;
1998
1999 case Instruction::Call: {
2000 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2001 if (!II) break;
2002 switch (II->getIntrinsicID()) {
2003 default: break;
2004
2005 // Binary vector operations that work column-wise. A dest element is a
2006 // function of the corresponding input elements from the two inputs.
2007 case Intrinsic::x86_sse_sub_ss:
2008 case Intrinsic::x86_sse_mul_ss:
2009 case Intrinsic::x86_sse_min_ss:
2010 case Intrinsic::x86_sse_max_ss:
2011 case Intrinsic::x86_sse2_sub_sd:
2012 case Intrinsic::x86_sse2_mul_sd:
2013 case Intrinsic::x86_sse2_min_sd:
2014 case Intrinsic::x86_sse2_max_sd:
2015 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2016 UndefElts, Depth+1);
2017 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2018 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2019 UndefElts2, Depth+1);
2020 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2021
2022 // If only the low elt is demanded and this is a scalarizable intrinsic,
2023 // scalarize it now.
2024 if (DemandedElts == 1) {
2025 switch (II->getIntrinsicID()) {
2026 default: break;
2027 case Intrinsic::x86_sse_sub_ss:
2028 case Intrinsic::x86_sse_mul_ss:
2029 case Intrinsic::x86_sse2_sub_sd:
2030 case Intrinsic::x86_sse2_mul_sd:
2031 // TODO: Lower MIN/MAX/ABS/etc
2032 Value *LHS = II->getOperand(1);
2033 Value *RHS = II->getOperand(2);
2034 // Extract the element as scalars.
2035 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2036 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2037
2038 switch (II->getIntrinsicID()) {
2039 default: assert(0 && "Case stmts out of sync!");
2040 case Intrinsic::x86_sse_sub_ss:
2041 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002042 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002043 II->getName()), *II);
2044 break;
2045 case Intrinsic::x86_sse_mul_ss:
2046 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002047 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002048 II->getName()), *II);
2049 break;
2050 }
2051
2052 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002053 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2054 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002055 InsertNewInstBefore(New, *II);
2056 AddSoonDeadInstToWorklist(*II, 0);
2057 return New;
2058 }
2059 }
2060
2061 // Output elements are undefined if both are undefined. Consider things
2062 // like undef&0. The result is known zero, not undef.
2063 UndefElts &= UndefElts2;
2064 break;
2065 }
2066 break;
2067 }
2068 }
2069 return MadeChange ? I : 0;
2070}
2071
Dan Gohman45b4e482008-05-19 22:14:15 +00002072/// ComputeNumSignBits - Return the number of times the sign bit of the
2073/// register is replicated into the other bits. We know that at least 1 bit
2074/// is always equal to the sign bit (itself), but other cases can give us
2075/// information. For example, immediately after an "ashr X, 2", we know that
2076/// the top 3 bits are all equal to each other, so we return 3.
2077///
2078unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2079 const IntegerType *Ty = cast<IntegerType>(V->getType());
2080 unsigned TyBits = Ty->getBitWidth();
2081 unsigned Tmp, Tmp2;
Dan Gohmana332f172008-05-23 02:28:01 +00002082 unsigned FirstAnswer = 1;
Dan Gohman45b4e482008-05-19 22:14:15 +00002083
2084 if (Depth == 6)
2085 return 1; // Limit search depth.
2086
2087 User *U = dyn_cast<User>(V);
2088 switch (getOpcode(V)) {
2089 default: break;
2090 case Instruction::SExt:
2091 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2092 return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2093
2094 case Instruction::AShr:
2095 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
Dan Gohmanf35c8822008-05-20 21:01:12 +00002096 // ashr X, C -> adds C sign bits.
Dan Gohman45b4e482008-05-19 22:14:15 +00002097 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2098 Tmp += C->getZExtValue();
2099 if (Tmp > TyBits) Tmp = TyBits;
2100 }
2101 return Tmp;
2102 case Instruction::Shl:
2103 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2104 // shl destroys sign bits.
2105 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2106 if (C->getZExtValue() >= TyBits || // Bad shift.
2107 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2108 return Tmp - C->getZExtValue();
2109 }
2110 break;
2111 case Instruction::And:
2112 case Instruction::Or:
Dan Gohmana332f172008-05-23 02:28:01 +00002113 case Instruction::Xor: // NOT is handled here.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002114 // Logical binary ops preserve the number of sign bits at the worst.
2115 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2116 if (Tmp != 1) {
2117 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohmana332f172008-05-23 02:28:01 +00002118 FirstAnswer = std::min(Tmp, Tmp2);
2119 // We computed what we know about the sign bits as our first
2120 // answer. Now proceed to the generic code that uses
2121 // ComputeMaskedBits, and pick whichever answer is better.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002122 }
Dan Gohmana332f172008-05-23 02:28:01 +00002123 break;
Dan Gohman45b4e482008-05-19 22:14:15 +00002124
2125 case Instruction::Select:
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002126 Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002127 if (Tmp == 1) return 1; // Early out.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002128 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002129 return std::min(Tmp, Tmp2);
2130
2131 case Instruction::Add:
2132 // Add can have at most one carry bit. Thus we know that the output
2133 // is, at worst, one more bit than the inputs.
2134 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2135 if (Tmp == 1) return 1; // Early out.
2136
2137 // Special case decrementing a value (ADD X, -1):
2138 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2139 if (CRHS->isAllOnesValue()) {
2140 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2141 APInt Mask = APInt::getAllOnesValue(TyBits);
2142 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2143
2144 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2145 // sign bits set.
2146 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2147 return TyBits;
2148
2149 // If we are subtracting one from a positive number, there is no carry
2150 // out of the result.
2151 if (KnownZero.isNegative())
2152 return Tmp;
2153 }
2154
2155 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2156 if (Tmp2 == 1) return 1;
2157 return std::min(Tmp, Tmp2)-1;
2158 break;
2159
2160 case Instruction::Sub:
2161 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2162 if (Tmp2 == 1) return 1;
2163
2164 // Handle NEG.
2165 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2166 if (CLHS->isNullValue()) {
2167 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2168 APInt Mask = APInt::getAllOnesValue(TyBits);
2169 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2170 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2171 // sign bits set.
2172 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2173 return TyBits;
2174
2175 // If the input is known to be positive (the sign bit is known clear),
2176 // the output of the NEG has the same number of sign bits as the input.
2177 if (KnownZero.isNegative())
2178 return Tmp2;
2179
2180 // Otherwise, we treat this like a SUB.
2181 }
2182
2183 // Sub can have at most one carry bit. Thus we know that the output
2184 // is, at worst, one more bit than the inputs.
2185 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2186 if (Tmp == 1) return 1; // Early out.
2187 return std::min(Tmp, Tmp2)-1;
2188 break;
2189 case Instruction::Trunc:
2190 // FIXME: it's tricky to do anything useful for this, but it is an important
2191 // case for targets like X86.
2192 break;
2193 }
2194
2195 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2196 // use this information.
2197 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2198 APInt Mask = APInt::getAllOnesValue(TyBits);
2199 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2200
2201 if (KnownZero.isNegative()) { // sign bit is 0
2202 Mask = KnownZero;
2203 } else if (KnownOne.isNegative()) { // sign bit is 1;
2204 Mask = KnownOne;
2205 } else {
2206 // Nothing known.
Dan Gohmana332f172008-05-23 02:28:01 +00002207 return FirstAnswer;
Dan Gohman45b4e482008-05-19 22:14:15 +00002208 }
2209
2210 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2211 // the number of identical bits in the top of the input value.
2212 Mask = ~Mask;
2213 Mask <<= Mask.getBitWidth()-TyBits;
2214 // Return # leading zeros. We use 'min' here in case Val was zero before
2215 // shifting. We don't want to return '64' as for an i32 "0".
Dan Gohmana332f172008-05-23 02:28:01 +00002216 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
Dan Gohman45b4e482008-05-19 22:14:15 +00002217}
2218
2219
Chris Lattner564a7272003-08-13 19:01:45 +00002220/// AssociativeOpt - Perform an optimization on an associative operator. This
2221/// function is designed to check a chain of associative operators for a
2222/// potential to apply a certain optimization. Since the optimization may be
2223/// applicable if the expression was reassociated, this checks the chain, then
2224/// reassociates the expression as necessary to expose the optimization
2225/// opportunity. This makes use of a special Functor, which must define
2226/// 'shouldApply' and 'apply' methods.
2227///
2228template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00002229static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00002230 unsigned Opcode = Root.getOpcode();
2231 Value *LHS = Root.getOperand(0);
2232
2233 // Quick check, see if the immediate LHS matches...
2234 if (F.shouldApply(LHS))
2235 return F.apply(Root);
2236
2237 // Otherwise, if the LHS is not of the same opcode as the root, return.
2238 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002239 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002240 // Should we apply this transform to the RHS?
2241 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2242
2243 // If not to the RHS, check to see if we should apply to the LHS...
2244 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2245 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2246 ShouldApply = true;
2247 }
2248
2249 // If the functor wants to apply the optimization to the RHS of LHSI,
2250 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2251 if (ShouldApply) {
2252 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002253
Chris Lattner564a7272003-08-13 19:01:45 +00002254 // Now all of the instructions are in the current basic block, go ahead
2255 // and perform the reassociation.
2256 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2257
2258 // First move the selected RHS to the LHS of the root...
2259 Root.setOperand(0, LHSI->getOperand(1));
2260
2261 // Make what used to be the LHS of the root be the user of the root...
2262 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002263 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002264 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2265 return 0;
2266 }
Chris Lattner65725312004-04-16 18:08:07 +00002267 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002268 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002269 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2270 BasicBlock::iterator ARI = &Root; ++ARI;
2271 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2272 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002273
2274 // Now propagate the ExtraOperand down the chain of instructions until we
2275 // get to LHSI.
2276 while (TmpLHSI != LHSI) {
2277 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002278 // Move the instruction to immediately before the chain we are
2279 // constructing to avoid breaking dominance properties.
2280 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2281 BB->getInstList().insert(ARI, NextLHSI);
2282 ARI = NextLHSI;
2283
Chris Lattner564a7272003-08-13 19:01:45 +00002284 Value *NextOp = NextLHSI->getOperand(1);
2285 NextLHSI->setOperand(1, ExtraOperand);
2286 TmpLHSI = NextLHSI;
2287 ExtraOperand = NextOp;
2288 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002289
Chris Lattner564a7272003-08-13 19:01:45 +00002290 // Now that the instructions are reassociated, have the functor perform
2291 // the transformation...
2292 return F.apply(Root);
2293 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002294
Chris Lattner564a7272003-08-13 19:01:45 +00002295 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2296 }
2297 return 0;
2298}
2299
Dan Gohman844731a2008-05-13 00:00:25 +00002300namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002301
Nick Lewycky02d639f2008-05-23 04:34:58 +00002302// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00002303struct AddRHS {
2304 Value *RHS;
2305 AddRHS(Value *rhs) : RHS(rhs) {}
2306 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2307 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00002308 return BinaryOperator::CreateShl(Add.getOperand(0),
2309 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002310 }
2311};
2312
2313// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2314// iff C1&C2 == 0
2315struct AddMaskingAnd {
2316 Constant *C2;
2317 AddMaskingAnd(Constant *c) : C2(c) {}
2318 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002319 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002320 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002321 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002322 }
2323 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002324 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002325 }
2326};
2327
Dan Gohman844731a2008-05-13 00:00:25 +00002328}
2329
Chris Lattner6e7ba452005-01-01 16:22:27 +00002330static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002331 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002332 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002333 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002334 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002335
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002336 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002337 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002338 }
2339
Chris Lattner2eefe512004-04-09 19:05:30 +00002340 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002341 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2342 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002343
Chris Lattner2eefe512004-04-09 19:05:30 +00002344 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2345 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002346 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2347 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002348 }
2349
2350 Value *Op0 = SO, *Op1 = ConstOperand;
2351 if (!ConstIsRHS)
2352 std::swap(Op0, Op1);
2353 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002354 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002355 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002356 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002357 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002358 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002359 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002360 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002361 abort();
2362 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002363 return IC->InsertNewInstBefore(New, I);
2364}
2365
2366// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2367// constant as the other operand, try to fold the binary operator into the
2368// select arguments. This also works for Cast instructions, which obviously do
2369// not have a second operand.
2370static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2371 InstCombiner *IC) {
2372 // Don't modify shared select instructions
2373 if (!SI->hasOneUse()) return 0;
2374 Value *TV = SI->getOperand(1);
2375 Value *FV = SI->getOperand(2);
2376
2377 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002378 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002379 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002380
Chris Lattner6e7ba452005-01-01 16:22:27 +00002381 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2382 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2383
Gabor Greif051a9502008-04-06 20:25:17 +00002384 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2385 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002386 }
2387 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002388}
2389
Chris Lattner4e998b22004-09-29 05:07:12 +00002390
2391/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2392/// node as operand #0, see if we can fold the instruction into the PHI (which
2393/// is only possible if all operands to the PHI are constants).
2394Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2395 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002396 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002397 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002398
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002399 // Check to see if all of the operands of the PHI are constants. If there is
2400 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002401 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002402 BasicBlock *NonConstBB = 0;
2403 for (unsigned i = 0; i != NumPHIValues; ++i)
2404 if (!isa<Constant>(PN->getIncomingValue(i))) {
2405 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002406 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002407 NonConstBB = PN->getIncomingBlock(i);
2408
2409 // If the incoming non-constant value is in I's block, we have an infinite
2410 // loop.
2411 if (NonConstBB == I.getParent())
2412 return 0;
2413 }
2414
2415 // If there is exactly one non-constant value, we can insert a copy of the
2416 // operation in that block. However, if this is a critical edge, we would be
2417 // inserting the computation one some other paths (e.g. inside a loop). Only
2418 // do this if the pred block is unconditionally branching into the phi block.
2419 if (NonConstBB) {
2420 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2421 if (!BI || !BI->isUnconditional()) return 0;
2422 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002423
2424 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002425 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002426 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002427 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002428 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002429
2430 // Next, add all of the operands to the PHI.
2431 if (I.getNumOperands() == 2) {
2432 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002433 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002434 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002435 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002436 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2437 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2438 else
2439 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002440 } else {
2441 assert(PN->getIncomingBlock(i) == NonConstBB);
2442 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002443 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002444 PN->getIncomingValue(i), C, "phitmp",
2445 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002446 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002447 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002448 CI->getPredicate(),
2449 PN->getIncomingValue(i), C, "phitmp",
2450 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002451 else
2452 assert(0 && "Unknown binop!");
2453
Chris Lattnerdbab3862007-03-02 21:28:56 +00002454 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002455 }
2456 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002457 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002458 } else {
2459 CastInst *CI = cast<CastInst>(&I);
2460 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002461 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002462 Value *InV;
2463 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002464 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002465 } else {
2466 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002467 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002468 I.getType(), "phitmp",
2469 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002470 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002471 }
2472 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002473 }
2474 }
2475 return ReplaceInstUsesWith(I, NewPN);
2476}
2477
Chris Lattner2454a2e2008-01-29 06:52:45 +00002478
2479/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2480/// value is never equal to -0.0.
2481///
2482/// Note that this function will need to be revisited when we support nondefault
2483/// rounding modes!
2484///
2485static bool CannotBeNegativeZero(const Value *V) {
2486 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2487 return !CFP->getValueAPF().isNegZero();
2488
Chris Lattner2454a2e2008-01-29 06:52:45 +00002489 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002490 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner2454a2e2008-01-29 06:52:45 +00002491 if (I->getOpcode() == Instruction::Add &&
2492 isa<ConstantFP>(I->getOperand(1)) &&
2493 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2494 return true;
2495
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002496 // sitofp and uitofp turn into +0.0 for zero.
2497 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2498 return true;
2499
Chris Lattner2454a2e2008-01-29 06:52:45 +00002500 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2501 if (II->getIntrinsicID() == Intrinsic::sqrt)
2502 return CannotBeNegativeZero(II->getOperand(1));
2503
2504 if (const CallInst *CI = dyn_cast<CallInst>(I))
2505 if (const Function *F = CI->getCalledFunction()) {
2506 if (F->isDeclaration()) {
2507 switch (F->getNameLen()) {
2508 case 3: // abs(x) != -0.0
2509 if (!strcmp(F->getNameStart(), "abs")) return true;
2510 break;
2511 case 4: // abs[lf](x) != -0.0
2512 if (!strcmp(F->getNameStart(), "absf")) return true;
2513 if (!strcmp(F->getNameStart(), "absl")) return true;
2514 break;
2515 }
2516 }
2517 }
2518 }
2519
2520 return false;
2521}
2522
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002523/// WillNotOverflowSignedAdd - Return true if we can prove that:
2524/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2525/// This basically requires proving that the add in the original type would not
2526/// overflow to change the sign bit or have a carry out.
2527bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2528 // There are different heuristics we can use for this. Here are some simple
2529 // ones.
2530
2531 // Add has the property that adding any two 2's complement numbers can only
2532 // have one carry bit which can change a sign. As such, if LHS and RHS each
2533 // have at least two sign bits, we know that the addition of the two values will
2534 // sign extend fine.
2535 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2536 return true;
2537
2538
2539 // If one of the operands only has one non-zero bit, and if the other operand
2540 // has a known-zero bit in a more significant place than it (not including the
2541 // sign bit) the ripple may go up to and fill the zero, but won't change the
2542 // sign. For example, (X & ~4) + 1.
2543
2544 // TODO: Implement.
2545
2546 return false;
2547}
2548
Chris Lattner2454a2e2008-01-29 06:52:45 +00002549
Chris Lattner7e708292002-06-25 16:13:24 +00002550Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002551 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002552 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002553
Chris Lattner66331a42004-04-10 22:01:55 +00002554 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002555 // X + undef -> undef
2556 if (isa<UndefValue>(RHS))
2557 return ReplaceInstUsesWith(I, RHS);
2558
Chris Lattner66331a42004-04-10 22:01:55 +00002559 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002560 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002561 if (RHSC->isNullValue())
2562 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002563 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002564 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2565 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002566 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002567 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002568
Chris Lattner66331a42004-04-10 22:01:55 +00002569 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002570 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002571 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002572 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002573 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002574 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002575
2576 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2577 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002578 if (!isa<VectorType>(I.getType())) {
2579 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2580 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2581 KnownZero, KnownOne))
2582 return &I;
2583 }
Chris Lattner66331a42004-04-10 22:01:55 +00002584 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002585
2586 if (isa<PHINode>(LHS))
2587 if (Instruction *NV = FoldOpIntoPhi(I))
2588 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002589
Chris Lattner4f637d42006-01-06 17:59:59 +00002590 ConstantInt *XorRHS = 0;
2591 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002592 if (isa<ConstantInt>(RHSC) &&
2593 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002594 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002595 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002596
Zhou Sheng4351c642007-04-02 08:20:41 +00002597 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002598 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2599 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002600 do {
2601 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002602 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2603 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002604 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2605 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002606 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002607 if (!MaskedValueIsZero(XorLHS,
2608 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002609 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002610 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002611 }
2612 }
2613 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002614 C0080Val = APIntOps::lshr(C0080Val, Size);
2615 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2616 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002617
Reid Spencer35c38852007-03-28 01:36:16 +00002618 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002619 // with funny bit widths then this switch statement should be removed. It
2620 // is just here to get the size of the "middle" type back up to something
2621 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002622 const Type *MiddleType = 0;
2623 switch (Size) {
2624 default: break;
2625 case 32: MiddleType = Type::Int32Ty; break;
2626 case 16: MiddleType = Type::Int16Ty; break;
2627 case 8: MiddleType = Type::Int8Ty; break;
2628 }
2629 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002630 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002631 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002632 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002633 }
2634 }
Chris Lattner66331a42004-04-10 22:01:55 +00002635 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002636
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002637 // X + X --> X << 1
Nick Lewycky02d639f2008-05-23 04:34:58 +00002638 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002639 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002640
2641 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2642 if (RHSI->getOpcode() == Instruction::Sub)
2643 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2644 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2645 }
2646 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2647 if (LHSI->getOpcode() == Instruction::Sub)
2648 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2649 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2650 }
Robert Bocchino71698282004-07-27 21:02:21 +00002651 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002652
Chris Lattner5c4afb92002-05-08 22:46:53 +00002653 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002654 // -A + -B --> -(A + B)
2655 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002656 if (LHS->getType()->isIntOrIntVector()) {
2657 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002658 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002659 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002660 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002661 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002662 }
2663
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002664 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002665 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002666
2667 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002668 if (!isa<Constant>(RHS))
2669 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002670 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002671
Misha Brukmanfd939082005-04-21 23:48:37 +00002672
Chris Lattner50af16a2004-11-13 19:50:12 +00002673 ConstantInt *C2;
2674 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2675 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002676 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002677
2678 // X*C1 + X*C2 --> X * (C1+C2)
2679 ConstantInt *C1;
2680 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002681 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002682 }
2683
2684 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002685 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002686 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002687
Chris Lattnere617c9e2007-01-05 02:17:46 +00002688 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002689 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2690 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002691
Chris Lattnerad3448c2003-02-18 19:57:07 +00002692
Chris Lattner564a7272003-08-13 19:01:45 +00002693 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002694 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002695 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2696 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002697
2698 // A+B --> A|B iff A and B have no bits set in common.
2699 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2700 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2701 APInt LHSKnownOne(IT->getBitWidth(), 0);
2702 APInt LHSKnownZero(IT->getBitWidth(), 0);
2703 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2704 if (LHSKnownZero != 0) {
2705 APInt RHSKnownOne(IT->getBitWidth(), 0);
2706 APInt RHSKnownZero(IT->getBitWidth(), 0);
2707 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2708
2709 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002710 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002711 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002712 }
2713 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002714
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002715 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002716 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002717 Value *W, *X, *Y, *Z;
2718 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2719 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2720 if (W != Y) {
2721 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002722 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002723 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002724 std::swap(W, X);
2725 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002726 std::swap(Y, Z);
2727 std::swap(W, X);
2728 }
2729 }
2730
2731 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002732 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002733 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002734 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002735 }
2736 }
2737 }
2738
Chris Lattner6b032052003-10-02 15:11:26 +00002739 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002740 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002741 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002742 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002743
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002744 // (X & FF00) + xx00 -> (X+xx00) & FF00
2745 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002746 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002747 if (Anded == CRHS) {
2748 // See if all bits from the first bit set in the Add RHS up are included
2749 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002750 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002751
2752 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002753 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002754
2755 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002756 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002757
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002758 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2759 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002760 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002761 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002762 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002763 }
2764 }
2765 }
2766
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002767 // Try to fold constant add into select arguments.
2768 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002769 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002770 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002771 }
2772
Reid Spencer1628cec2006-10-26 06:15:43 +00002773 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002774 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002775 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002776 CastInst *CI = dyn_cast<CastInst>(LHS);
2777 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002778 if (!CI) {
2779 CI = dyn_cast<CastInst>(RHS);
2780 Other = LHS;
2781 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002782 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002783 (CI->getType()->getPrimitiveSizeInBits() ==
2784 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002785 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002786 unsigned AS =
2787 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002788 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2789 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002790 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002791 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002792 }
2793 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002794
Chris Lattner42790482007-12-20 01:56:58 +00002795 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002796 {
2797 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2798 Value *Other = RHS;
2799 if (!SI) {
2800 SI = dyn_cast<SelectInst>(RHS);
2801 Other = LHS;
2802 }
Chris Lattner42790482007-12-20 01:56:58 +00002803 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002804 Value *TV = SI->getTrueValue();
2805 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002806 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002807
2808 // Can we fold the add into the argument of the select?
2809 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002810 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2811 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002812 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002813 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2814 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002815 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002816 }
2817 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002818
2819 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2820 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2821 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2822 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002823
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002824 // Check for (add (sext x), y), see if we can merge this into an
2825 // integer add followed by a sext.
2826 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2827 // (add (sext x), cst) --> (sext (add x, cst'))
2828 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2829 Constant *CI =
2830 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2831 if (LHSConv->hasOneUse() &&
2832 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2833 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2834 // Insert the new, smaller add.
2835 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2836 CI, "addconv");
2837 InsertNewInstBefore(NewAdd, I);
2838 return new SExtInst(NewAdd, I.getType());
2839 }
2840 }
2841
2842 // (add (sext x), (sext y)) --> (sext (add int x, y))
2843 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2844 // Only do this if x/y have the same type, if at last one of them has a
2845 // single use (so we don't increase the number of sexts), and if the
2846 // integer add will not overflow.
2847 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2848 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2849 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2850 RHSConv->getOperand(0))) {
2851 // Insert the new integer add.
2852 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2853 RHSConv->getOperand(0),
2854 "addconv");
2855 InsertNewInstBefore(NewAdd, I);
2856 return new SExtInst(NewAdd, I.getType());
2857 }
2858 }
2859 }
2860
2861 // Check for (add double (sitofp x), y), see if we can merge this into an
2862 // integer add followed by a promotion.
2863 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2864 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2865 // ... if the constant fits in the integer value. This is useful for things
2866 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2867 // requires a constant pool load, and generally allows the add to be better
2868 // instcombined.
2869 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2870 Constant *CI =
2871 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2872 if (LHSConv->hasOneUse() &&
2873 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2874 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2875 // Insert the new integer add.
2876 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2877 CI, "addconv");
2878 InsertNewInstBefore(NewAdd, I);
2879 return new SIToFPInst(NewAdd, I.getType());
2880 }
2881 }
2882
2883 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2884 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2885 // Only do this if x/y have the same type, if at last one of them has a
2886 // single use (so we don't increase the number of int->fp conversions),
2887 // and if the integer add will not overflow.
2888 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2889 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2890 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2891 RHSConv->getOperand(0))) {
2892 // Insert the new integer add.
2893 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2894 RHSConv->getOperand(0),
2895 "addconv");
2896 InsertNewInstBefore(NewAdd, I);
2897 return new SIToFPInst(NewAdd, I.getType());
2898 }
2899 }
2900 }
2901
Chris Lattner7e708292002-06-25 16:13:24 +00002902 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002903}
2904
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002905// isSignBit - Return true if the value represented by the constant only has the
2906// highest order bit set.
2907static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002908 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002909 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002910}
2911
Chris Lattner7e708292002-06-25 16:13:24 +00002912Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002913 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002914
Chris Lattner233f7dc2002-08-12 21:17:25 +00002915 if (Op0 == Op1) // sub X, X -> 0
2916 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002917
Chris Lattner233f7dc2002-08-12 21:17:25 +00002918 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002919 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002920 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002921
Chris Lattnere87597f2004-10-16 18:11:37 +00002922 if (isa<UndefValue>(Op0))
2923 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2924 if (isa<UndefValue>(Op1))
2925 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2926
Chris Lattnerd65460f2003-11-05 01:06:05 +00002927 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2928 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002929 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002930 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002931
Chris Lattnerd65460f2003-11-05 01:06:05 +00002932 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002933 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002934 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002935 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002936
Chris Lattner76b7a062007-01-15 07:02:54 +00002937 // -(X >>u 31) -> (X >>s 31)
2938 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002939 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002940 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002941 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002942 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002943 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002944 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002945 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002946 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002947 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002948 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002949 }
2950 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002951 }
2952 else if (SI->getOpcode() == Instruction::AShr) {
2953 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2954 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002955 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002956 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002957 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002958 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002959 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002960 }
2961 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002962 }
2963 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002964 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002965
2966 // Try to fold constant sub into select arguments.
2967 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002968 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002969 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002970
2971 if (isa<PHINode>(Op0))
2972 if (Instruction *NV = FoldOpIntoPhi(I))
2973 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002974 }
2975
Chris Lattner43d84d62005-04-07 16:15:25 +00002976 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2977 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002978 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002979 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002980 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002981 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002982 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002983 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2984 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2985 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002986 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002987 Op1I->getOperand(0));
2988 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002989 }
2990
Chris Lattnerfd059242003-10-15 16:48:29 +00002991 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002992 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2993 // is not used by anyone else...
2994 //
Chris Lattner0517e722004-02-02 20:09:56 +00002995 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002996 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002997 // Swap the two operands of the subexpr...
2998 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2999 Op1I->setOperand(0, IIOp1);
3000 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00003001
Chris Lattnera2881962003-02-18 19:28:33 +00003002 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003003 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003004 }
3005
3006 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3007 //
3008 if (Op1I->getOpcode() == Instruction::And &&
3009 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3010 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3011
Chris Lattnerf523d062004-06-09 05:08:07 +00003012 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003013 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3014 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00003015 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00003016
Reid Spencerac5209e2006-10-16 23:08:08 +00003017 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00003018 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00003019 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00003020 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00003021 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003022 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00003023 ConstantExpr::getNeg(DivRHS));
3024
Chris Lattnerad3448c2003-02-18 19:57:07 +00003025 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00003026 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00003027 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003028 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003029 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00003030 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00003031
3032 // X - ((X / Y) * Y) --> X % Y
3033 if (Op1I->getOpcode() == Instruction::Mul)
3034 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3035 if (Op0 == I->getOperand(0) &&
3036 Op1I->getOperand(1) == I->getOperand(1)) {
3037 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003038 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003039 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003040 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003041 }
Chris Lattner40371712002-05-09 01:29:19 +00003042 }
Chris Lattner43d84d62005-04-07 16:15:25 +00003043 }
Chris Lattnera2881962003-02-18 19:28:33 +00003044
Chris Lattner9919e3d2006-12-02 00:13:08 +00003045 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003046 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00003047 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003048 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
3049 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3050 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
3051 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00003052 } else if (Op0I->getOpcode() == Instruction::Sub) {
3053 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003054 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003055 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003056 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003057
Chris Lattner50af16a2004-11-13 19:50:12 +00003058 ConstantInt *C1;
3059 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003060 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003061 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00003062
Chris Lattner50af16a2004-11-13 19:50:12 +00003063 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
3064 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003065 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00003066 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003067 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003068}
3069
Chris Lattnera0141b92007-07-15 20:42:37 +00003070/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3071/// comparison only checks the sign bit. If it only checks the sign bit, set
3072/// TrueIfSigned if the result of the comparison is true when the input value is
3073/// signed.
3074static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3075 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003076 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003077 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3078 TrueIfSigned = true;
3079 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003080 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3081 TrueIfSigned = true;
3082 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00003083 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3084 TrueIfSigned = false;
3085 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003086 case ICmpInst::ICMP_UGT:
3087 // True if LHS u> RHS and RHS == high-bit-mask - 1
3088 TrueIfSigned = true;
3089 return RHS->getValue() ==
3090 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3091 case ICmpInst::ICMP_UGE:
3092 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3093 TrueIfSigned = true;
3094 return RHS->getValue() ==
3095 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00003096 default:
3097 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00003098 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00003099}
3100
Chris Lattner7e708292002-06-25 16:13:24 +00003101Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003102 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00003103 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003104
Chris Lattnere87597f2004-10-16 18:11:37 +00003105 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
3106 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3107
Chris Lattner233f7dc2002-08-12 21:17:25 +00003108 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00003109 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3110 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00003111
3112 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00003113 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00003114 if (SI->getOpcode() == Instruction::Shl)
3115 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003116 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003117 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003118
Zhou Sheng843f07672007-04-19 05:39:12 +00003119 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00003120 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
3121 if (CI->equalsInt(1)) // X * 1 == X
3122 return ReplaceInstUsesWith(I, Op0);
3123 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003124 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003125
Zhou Sheng97b52c22007-03-29 01:57:21 +00003126 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003127 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003128 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00003129 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003130 }
Robert Bocchino71698282004-07-27 21:02:21 +00003131 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00003132 if (Op1F->isNullValue())
3133 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00003134
Chris Lattnera2881962003-02-18 19:28:33 +00003135 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3136 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00003137 // We need a better interface for long double here.
3138 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3139 if (Op1F->isExactlyValue(1.0))
3140 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00003141 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003142
3143 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3144 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00003145 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003146 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003147 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003148 Op1, "tmp");
3149 InsertNewInstBefore(Add, I);
3150 Value *C1C2 = ConstantExpr::getMul(Op1,
3151 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003152 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003153
3154 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003155
3156 // Try to fold constant mul into select arguments.
3157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003159 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003160
3161 if (isa<PHINode>(Op0))
3162 if (Instruction *NV = FoldOpIntoPhi(I))
3163 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003164 }
3165
Chris Lattnera4f445b2003-03-10 23:23:04 +00003166 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3167 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003168 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003169
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003170 // If one of the operands of the multiply is a cast from a boolean value, then
3171 // we know the bool is either zero or one, so this is a 'masking' multiply.
3172 // See if we can simplify things based on how the boolean was originally
3173 // formed.
3174 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00003175 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003176 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003177 BoolCast = CI;
3178 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00003179 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003180 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003181 BoolCast = CI;
3182 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003183 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003184 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3185 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00003186 bool TIS = false;
3187
Reid Spencere4d87aa2006-12-23 06:05:41 +00003188 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00003189 // multiply into a shift/and combination.
3190 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00003191 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3192 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003193 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00003194 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00003195 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00003196 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00003197 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003198 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00003199 BoolCast->getOperand(0)->getName()+
3200 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003201
3202 // If the multiply type is not the same as the source type, sign extend
3203 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00003204 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00003205 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3206 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00003207 Instruction::CastOps opcode =
3208 (SrcBits == DstBits ? Instruction::BitCast :
3209 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3210 V = InsertCastBefore(opcode, V, I.getType(), I);
3211 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003212
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003213 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003214 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003215 }
3216 }
3217 }
3218
Chris Lattner7e708292002-06-25 16:13:24 +00003219 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003220}
3221
Reid Spencer1628cec2006-10-26 06:15:43 +00003222/// This function implements the transforms on div instructions that work
3223/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3224/// used by the visitors to those instructions.
3225/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003226Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003227 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003228
Chris Lattner50b2ca42008-02-19 06:12:18 +00003229 // undef / X -> 0 for integer.
3230 // undef / X -> undef for FP (the undef could be a snan).
3231 if (isa<UndefValue>(Op0)) {
3232 if (Op0->getType()->isFPOrFPVector())
3233 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003234 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003235 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003236
3237 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003238 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003239 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003240
Chris Lattner25feae52008-01-28 00:58:18 +00003241 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3242 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00003243 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00003244 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
3245 // the same basic block, then we replace the select with Y, and the
3246 // condition of the select with false (if the cond value is in the same BB).
3247 // If the select has uses other than the div, this allows them to be
3248 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3249 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003250 if (ST->isNullValue()) {
3251 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3252 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003253 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00003254 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3255 I.setOperand(1, SI->getOperand(2));
3256 else
3257 UpdateValueUsesWith(SI, SI->getOperand(2));
3258 return &I;
3259 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003260
Chris Lattner25feae52008-01-28 00:58:18 +00003261 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3262 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003263 if (ST->isNullValue()) {
3264 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3265 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003266 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00003267 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3268 I.setOperand(1, SI->getOperand(1));
3269 else
3270 UpdateValueUsesWith(SI, SI->getOperand(1));
3271 return &I;
3272 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003273 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003274
Reid Spencer1628cec2006-10-26 06:15:43 +00003275 return 0;
3276}
Misha Brukmanfd939082005-04-21 23:48:37 +00003277
Reid Spencer1628cec2006-10-26 06:15:43 +00003278/// This function implements the transforms common to both integer division
3279/// instructions (udiv and sdiv). It is called by the visitors to those integer
3280/// division instructions.
3281/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003282Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003283 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3284
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003285 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003286 if (Op0 == Op1) {
3287 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3288 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
3289 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3290 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3291 }
3292
3293 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
3294 return ReplaceInstUsesWith(I, CI);
3295 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003296
Reid Spencer1628cec2006-10-26 06:15:43 +00003297 if (Instruction *Common = commonDivTransforms(I))
3298 return Common;
3299
3300 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3301 // div X, 1 == X
3302 if (RHS->equalsInt(1))
3303 return ReplaceInstUsesWith(I, Op0);
3304
3305 // (X / C1) / C2 -> X / (C1*C2)
3306 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3307 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3308 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003309 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3310 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3311 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003312 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003313 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003314 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003315
Reid Spencerbca0e382007-03-23 20:05:17 +00003316 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003317 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3318 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3319 return R;
3320 if (isa<PHINode>(Op0))
3321 if (Instruction *NV = FoldOpIntoPhi(I))
3322 return NV;
3323 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003324 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003325
Chris Lattnera2881962003-02-18 19:28:33 +00003326 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003327 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003328 if (LHS->equalsInt(0))
3329 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3330
Reid Spencer1628cec2006-10-26 06:15:43 +00003331 return 0;
3332}
3333
3334Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3335 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3336
3337 // Handle the integer div common cases
3338 if (Instruction *Common = commonIDivTransforms(I))
3339 return Common;
3340
3341 // X udiv C^2 -> X >> C
3342 // Check to see if this is an unsigned division with an exact power of 2,
3343 // if so, convert to a right shift.
3344 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003345 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003346 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003347 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003348 }
3349
3350 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003351 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003352 if (RHSI->getOpcode() == Instruction::Shl &&
3353 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003354 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003355 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003356 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003357 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003358 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003359 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003360 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003361 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003362 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003363 }
3364 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003365 }
3366
Reid Spencer1628cec2006-10-26 06:15:43 +00003367 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3368 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003369 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003370 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003371 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003372 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003373 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003374 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003375 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003376 // Construct the "on true" case of the select
3377 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003378 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003379 Op0, TC, SI->getName()+".t");
3380 TSI = InsertNewInstBefore(TSI, I);
3381
3382 // Construct the "on false" case of the select
3383 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003384 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003385 Op0, FC, SI->getName()+".f");
3386 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003387
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003388 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003389 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003390 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003391 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003392 return 0;
3393}
3394
Reid Spencer1628cec2006-10-26 06:15:43 +00003395Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3396 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3397
3398 // Handle the integer div common cases
3399 if (Instruction *Common = commonIDivTransforms(I))
3400 return Common;
3401
3402 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3403 // sdiv X, -1 == -X
3404 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003405 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003406
3407 // -X/C -> X/-C
3408 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003409 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003410 }
3411
3412 // If the sign bits of both operands are zero (i.e. we can prove they are
3413 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003414 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003415 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003416 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003417 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003418 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003419 }
3420 }
3421
3422 return 0;
3423}
3424
3425Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3426 return commonDivTransforms(I);
3427}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003428
Reid Spencer0a783f72006-11-02 01:53:59 +00003429/// This function implements the transforms on rem instructions that work
3430/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3431/// is used by the visitors to those instructions.
3432/// @brief Transforms common to all three rem instructions
3433Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003434 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003435
Chris Lattner50b2ca42008-02-19 06:12:18 +00003436 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003437 if (Constant *LHS = dyn_cast<Constant>(Op0))
3438 if (LHS->isNullValue())
3439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3440
Chris Lattner50b2ca42008-02-19 06:12:18 +00003441 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3442 if (I.getType()->isFPOrFPVector())
3443 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003444 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003445 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003446 if (isa<UndefValue>(Op1))
3447 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003448
3449 // Handle cases involving: rem X, (select Cond, Y, Z)
3450 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3451 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3452 // the same basic block, then we replace the select with Y, and the
3453 // condition of the select with false (if the cond value is in the same
3454 // BB). If the select has uses other than the div, this allows them to be
3455 // simplified also.
3456 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3457 if (ST->isNullValue()) {
3458 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3459 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003460 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003461 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3462 I.setOperand(1, SI->getOperand(2));
3463 else
3464 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003465 return &I;
3466 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003467 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3468 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3469 if (ST->isNullValue()) {
3470 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3471 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003472 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003473 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3474 I.setOperand(1, SI->getOperand(1));
3475 else
3476 UpdateValueUsesWith(SI, SI->getOperand(1));
3477 return &I;
3478 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003479 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003480
Reid Spencer0a783f72006-11-02 01:53:59 +00003481 return 0;
3482}
3483
3484/// This function implements the transforms common to both integer remainder
3485/// instructions (urem and srem). It is called by the visitors to those integer
3486/// remainder instructions.
3487/// @brief Common integer remainder transforms
3488Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3489 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3490
3491 if (Instruction *common = commonRemTransforms(I))
3492 return common;
3493
Chris Lattner857e8cd2004-12-12 21:48:58 +00003494 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003495 // X % 0 == undef, we don't need to preserve faults!
3496 if (RHS->equalsInt(0))
3497 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3498
Chris Lattnera2881962003-02-18 19:28:33 +00003499 if (RHS->equalsInt(1)) // X % 1 == 0
3500 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3501
Chris Lattner97943922006-02-28 05:49:21 +00003502 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3503 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3504 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3505 return R;
3506 } else if (isa<PHINode>(Op0I)) {
3507 if (Instruction *NV = FoldOpIntoPhi(I))
3508 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003509 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003510
3511 // See if we can fold away this rem instruction.
3512 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3513 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3514 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3515 KnownZero, KnownOne))
3516 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003517 }
Chris Lattnera2881962003-02-18 19:28:33 +00003518 }
3519
Reid Spencer0a783f72006-11-02 01:53:59 +00003520 return 0;
3521}
3522
3523Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3524 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3525
3526 if (Instruction *common = commonIRemTransforms(I))
3527 return common;
3528
3529 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3530 // X urem C^2 -> X and C
3531 // Check to see if this is an unsigned remainder with an exact power of 2,
3532 // if so, convert to a bitwise and.
3533 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003534 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003535 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003536 }
3537
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003538 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003539 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3540 if (RHSI->getOpcode() == Instruction::Shl &&
3541 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003542 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003543 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003544 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003545 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003546 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003547 }
3548 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003549 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003550
Reid Spencer0a783f72006-11-02 01:53:59 +00003551 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3552 // where C1&C2 are powers of two.
3553 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3554 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3555 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3556 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003557 if ((STO->getValue().isPowerOf2()) &&
3558 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003559 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003560 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003561 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003562 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003563 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003564 }
3565 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003566 }
3567
Chris Lattner3f5b8772002-05-06 16:14:14 +00003568 return 0;
3569}
3570
Reid Spencer0a783f72006-11-02 01:53:59 +00003571Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3572 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3573
Dan Gohmancff55092007-11-05 23:16:33 +00003574 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003575 if (Instruction *common = commonIRemTransforms(I))
3576 return common;
3577
3578 if (Value *RHSNeg = dyn_castNegVal(Op1))
3579 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003580 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003581 // X % -Y -> X % Y
3582 AddUsesToWorkList(I);
3583 I.setOperand(1, RHSNeg);
3584 return &I;
3585 }
3586
Dan Gohmancff55092007-11-05 23:16:33 +00003587 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003588 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003589 if (I.getType()->isInteger()) {
3590 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3591 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3592 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003593 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003594 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003595 }
3596
3597 return 0;
3598}
3599
3600Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003601 return commonRemTransforms(I);
3602}
3603
Chris Lattner8b170942002-08-09 23:47:40 +00003604// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003605static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003606 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003607 if (!isSigned)
3608 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3609 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003610}
3611
3612// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003613static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003614 if (!isSigned)
3615 return C->getValue() == 1; // unsigned
3616
3617 // Calculate 1111111111000000000000
3618 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3619 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003620}
3621
Chris Lattner457dd822004-06-09 07:59:58 +00003622// isOneBitSet - Return true if there is exactly one bit set in the specified
3623// constant.
3624static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003625 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003626}
3627
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003628// isHighOnes - Return true if the constant is of the form 1+0+.
3629// This is the same as lowones(~X).
3630static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003631 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003632}
3633
Reid Spencere4d87aa2006-12-23 06:05:41 +00003634/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003635/// are carefully arranged to allow folding of expressions such as:
3636///
3637/// (A < B) | (A > B) --> (A != B)
3638///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639/// Note that this is only valid if the first and second predicates have the
3640/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003641///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003642/// Three bits are used to represent the condition, as follows:
3643/// 0 A > B
3644/// 1 A == B
3645/// 2 A < B
3646///
3647/// <=> Value Definition
3648/// 000 0 Always false
3649/// 001 1 A > B
3650/// 010 2 A == B
3651/// 011 3 A >= B
3652/// 100 4 A < B
3653/// 101 5 A != B
3654/// 110 6 A <= B
3655/// 111 7 Always true
3656///
3657static unsigned getICmpCode(const ICmpInst *ICI) {
3658 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003659 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003660 case ICmpInst::ICMP_UGT: return 1; // 001
3661 case ICmpInst::ICMP_SGT: return 1; // 001
3662 case ICmpInst::ICMP_EQ: return 2; // 010
3663 case ICmpInst::ICMP_UGE: return 3; // 011
3664 case ICmpInst::ICMP_SGE: return 3; // 011
3665 case ICmpInst::ICMP_ULT: return 4; // 100
3666 case ICmpInst::ICMP_SLT: return 4; // 100
3667 case ICmpInst::ICMP_NE: return 5; // 101
3668 case ICmpInst::ICMP_ULE: return 6; // 110
3669 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003670 // True -> 7
3671 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003672 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003673 return 0;
3674 }
3675}
3676
Reid Spencere4d87aa2006-12-23 06:05:41 +00003677/// getICmpValue - This is the complement of getICmpCode, which turns an
3678/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003679/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003680/// of predicate to use in new icmp instructions.
3681static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3682 switch (code) {
3683 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003684 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003685 case 1:
3686 if (sign)
3687 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3688 else
3689 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3690 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3691 case 3:
3692 if (sign)
3693 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3694 else
3695 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3696 case 4:
3697 if (sign)
3698 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3699 else
3700 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3701 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3702 case 6:
3703 if (sign)
3704 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3705 else
3706 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003707 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003708 }
3709}
3710
Reid Spencere4d87aa2006-12-23 06:05:41 +00003711static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3712 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3713 (ICmpInst::isSignedPredicate(p1) &&
3714 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3715 (ICmpInst::isSignedPredicate(p2) &&
3716 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3717}
3718
3719namespace {
3720// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3721struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003722 InstCombiner &IC;
3723 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003724 ICmpInst::Predicate pred;
3725 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3726 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3727 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003728 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003729 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3730 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003731 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3732 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003733 return false;
3734 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003735 Instruction *apply(Instruction &Log) const {
3736 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3737 if (ICI->getOperand(0) != LHS) {
3738 assert(ICI->getOperand(1) == LHS);
3739 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003740 }
3741
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003742 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003743 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003744 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003745 unsigned Code;
3746 switch (Log.getOpcode()) {
3747 case Instruction::And: Code = LHSCode & RHSCode; break;
3748 case Instruction::Or: Code = LHSCode | RHSCode; break;
3749 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003750 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003751 }
3752
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003753 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3754 ICmpInst::isSignedPredicate(ICI->getPredicate());
3755
3756 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003757 if (Instruction *I = dyn_cast<Instruction>(RV))
3758 return I;
3759 // Otherwise, it's a constant boolean value...
3760 return IC.ReplaceInstUsesWith(Log, RV);
3761 }
3762};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003763} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003764
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003765// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3766// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003767// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003768Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003769 ConstantInt *OpRHS,
3770 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003771 BinaryOperator &TheAnd) {
3772 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003773 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003774 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003775 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003776
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003777 switch (Op->getOpcode()) {
3778 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003779 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003780 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003781 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003782 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003783 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003784 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003785 }
3786 break;
3787 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003788 if (Together == AndRHS) // (X | C) & C --> C
3789 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003790
Chris Lattner6e7ba452005-01-01 16:22:27 +00003791 if (Op->hasOneUse() && Together != OpRHS) {
3792 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003793 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003794 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003795 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003796 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003797 }
3798 break;
3799 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003800 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003801 // Adding a one to a single bit bit-field should be turned into an XOR
3802 // of the bit. First thing to check is to see if this AND is with a
3803 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003804 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003805
3806 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003807 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003808 // Ok, at this point, we know that we are masking the result of the
3809 // ADD down to exactly one bit. If the constant we are adding has
3810 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003811 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003812
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003813 // Check to see if any bits below the one bit set in AndRHSV are set.
3814 if ((AddRHS & (AndRHSV-1)) == 0) {
3815 // If not, the only thing that can effect the output of the AND is
3816 // the bit specified by AndRHSV. If that bit is set, the effect of
3817 // the XOR is to toggle the bit. If it is clear, then the ADD has
3818 // no effect.
3819 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3820 TheAnd.setOperand(0, X);
3821 return &TheAnd;
3822 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003823 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003824 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003825 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003826 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003827 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003828 }
3829 }
3830 }
3831 }
3832 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003833
3834 case Instruction::Shl: {
3835 // We know that the AND will not produce any of the bits shifted in, so if
3836 // the anded constant includes them, clear them now!
3837 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003838 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003839 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003840 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3841 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003842
Zhou Sheng290bec52007-03-29 08:15:12 +00003843 if (CI->getValue() == ShlMask) {
3844 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003845 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3846 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003847 TheAnd.setOperand(1, CI);
3848 return &TheAnd;
3849 }
3850 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003851 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003852 case Instruction::LShr:
3853 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003854 // We know that the AND will not produce any of the bits shifted in, so if
3855 // the anded constant includes them, clear them now! This only applies to
3856 // unsigned shifts, because a signed shr may bring in set bits!
3857 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003858 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003859 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003860 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3861 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003862
Zhou Sheng290bec52007-03-29 08:15:12 +00003863 if (CI->getValue() == ShrMask) {
3864 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003865 return ReplaceInstUsesWith(TheAnd, Op);
3866 } else if (CI != AndRHS) {
3867 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3868 return &TheAnd;
3869 }
3870 break;
3871 }
3872 case Instruction::AShr:
3873 // Signed shr.
3874 // See if this is shifting in some sign extension, then masking it out
3875 // with an and.
3876 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003877 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003878 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003879 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3880 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003881 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003882 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003883 // Make the argument unsigned.
3884 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003885 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003886 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003887 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003888 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003889 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003890 }
3891 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003892 }
3893 return 0;
3894}
3895
Chris Lattner8b170942002-08-09 23:47:40 +00003896
Chris Lattnera96879a2004-09-29 17:40:11 +00003897/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3898/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003899/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3900/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003901/// insert new instructions.
3902Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003903 bool isSigned, bool Inside,
3904 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003905 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003906 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003907 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003908
Chris Lattnera96879a2004-09-29 17:40:11 +00003909 if (Inside) {
3910 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003911 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003912
Reid Spencere4d87aa2006-12-23 06:05:41 +00003913 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003914 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003915 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003916 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3917 return new ICmpInst(pred, V, Hi);
3918 }
3919
3920 // Emit V-Lo <u Hi-Lo
3921 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003922 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003923 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003924 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3925 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003926 }
3927
3928 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003929 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003930
Reid Spencere4e40032007-03-21 23:19:50 +00003931 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003932 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003933 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003934 ICmpInst::Predicate pred = (isSigned ?
3935 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3936 return new ICmpInst(pred, V, Hi);
3937 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003938
Reid Spencere4e40032007-03-21 23:19:50 +00003939 // Emit V-Lo >u Hi-1-Lo
3940 // Note that Hi has already had one subtracted from it, above.
3941 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003942 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003943 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003944 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3945 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003946}
3947
Chris Lattner7203e152005-09-18 07:22:02 +00003948// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3949// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3950// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3951// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003952static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003953 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003954 uint32_t BitWidth = Val->getType()->getBitWidth();
3955 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003956
3957 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003958 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003959 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003960 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003961 return true;
3962}
3963
Chris Lattner7203e152005-09-18 07:22:02 +00003964/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3965/// where isSub determines whether the operator is a sub. If we can fold one of
3966/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003967///
3968/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3969/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3970/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3971///
3972/// return (A +/- B).
3973///
3974Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003975 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003976 Instruction &I) {
3977 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3978 if (!LHSI || LHSI->getNumOperands() != 2 ||
3979 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3980
3981 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3982
3983 switch (LHSI->getOpcode()) {
3984 default: return 0;
3985 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003986 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003987 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003988 if ((Mask->getValue().countLeadingZeros() +
3989 Mask->getValue().countPopulation()) ==
3990 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003991 break;
3992
3993 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3994 // part, we don't need any explicit masks to take them out of A. If that
3995 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003996 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003997 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003998 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003999 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004000 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004001 break;
4002 }
4003 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004004 return 0;
4005 case Instruction::Or:
4006 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004007 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004008 if ((Mask->getValue().countLeadingZeros() +
4009 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00004010 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004011 break;
4012 return 0;
4013 }
4014
4015 Instruction *New;
4016 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004017 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004018 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004019 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004020 return InsertNewInstBefore(New, I);
4021}
4022
Chris Lattner7e708292002-06-25 16:13:24 +00004023Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004024 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004025 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004026
Chris Lattnere87597f2004-10-16 18:11:37 +00004027 if (isa<UndefValue>(Op1)) // X & undef -> 0
4028 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4029
Chris Lattner6e7ba452005-01-01 16:22:27 +00004030 // and X, X = X
4031 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004032 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004033
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004034 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004035 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00004036 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00004037 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4038 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4039 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00004040 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00004041 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00004042 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004043 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004044 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004045 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004046 } else if (isa<ConstantAggregateZero>(Op1)) {
4047 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004048 }
4049 }
Chris Lattner9ca96412006-02-08 03:25:32 +00004050
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004051 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004052 const APInt& AndRHSMask = AndRHS->getValue();
4053 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004054
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004055 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004056 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004057 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004058 Value *Op0LHS = Op0I->getOperand(0);
4059 Value *Op0RHS = Op0I->getOperand(1);
4060 switch (Op0I->getOpcode()) {
4061 case Instruction::Xor:
4062 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004063 // If the mask is only needed on one incoming arm, push it up.
4064 if (Op0I->hasOneUse()) {
4065 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4066 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004067 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004068 Op0RHS->getName()+".masked");
4069 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004070 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004071 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004072 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004073 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004074 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4075 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004076 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004077 Op0LHS->getName()+".masked");
4078 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004079 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004080 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4081 }
4082 }
4083
Chris Lattner6e7ba452005-01-01 16:22:27 +00004084 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004085 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004086 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4087 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4088 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4089 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004090 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004091 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004092 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004093 break;
4094
4095 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004096 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4097 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4098 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4099 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004100 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00004101 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004102 }
4103
Chris Lattner58403262003-07-23 19:25:52 +00004104 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004105 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004106 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004107 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004108 // If this is an integer truncation or change from signed-to-unsigned, and
4109 // if the source is an and/or with immediate, transform it. This
4110 // frequently occurs for bitfield accesses.
4111 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004112 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004113 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004114 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004115 if (CastOp->getOpcode() == Instruction::And) {
4116 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004117 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4118 // This will fold the two constants together, which may allow
4119 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004120 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004121 CastOp->getOperand(0), I.getType(),
4122 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004123 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004124 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00004125 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00004126 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004127 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004128 } else if (CastOp->getOpcode() == Instruction::Or) {
4129 // Change: and (cast (or X, C1) to T), C2
4130 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00004131 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00004132 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4133 return ReplaceInstUsesWith(I, AndRHS);
4134 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004135 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004136 }
Chris Lattner06782f82003-07-23 19:36:21 +00004137 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004138
4139 // Try to fold constant and into select arguments.
4140 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004141 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004142 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004143 if (isa<PHINode>(Op0))
4144 if (Instruction *NV = FoldOpIntoPhi(I))
4145 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004146 }
4147
Chris Lattner8d969642003-03-10 23:06:50 +00004148 Value *Op0NotVal = dyn_castNotVal(Op0);
4149 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004150
Chris Lattner5b62aa72004-06-18 06:07:51 +00004151 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4152 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4153
Misha Brukmancb6267b2004-07-30 12:50:08 +00004154 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004155 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004156 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004157 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004158 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004159 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004160 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004161
4162 {
Chris Lattner003b6202007-06-15 05:58:24 +00004163 Value *A = 0, *B = 0, *C = 0, *D = 0;
4164 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004165 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4166 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004167
4168 // (A|B) & ~(A&B) -> A^B
4169 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4170 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004171 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004172 }
4173 }
4174
4175 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004176 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4177 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004178
4179 // ~(A&B) & (A|B) -> A^B
4180 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4181 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004182 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004183 }
4184 }
Chris Lattner64daab52006-04-01 08:03:55 +00004185
4186 if (Op0->hasOneUse() &&
4187 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4188 if (A == Op1) { // (A^B)&A -> A&(A^B)
4189 I.swapOperands(); // Simplify below
4190 std::swap(Op0, Op1);
4191 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4192 cast<BinaryOperator>(Op0)->swapOperands();
4193 I.swapOperands(); // Simplify below
4194 std::swap(Op0, Op1);
4195 }
4196 }
4197 if (Op1->hasOneUse() &&
4198 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4199 if (B == Op0) { // B&(A^B) -> B&(B^A)
4200 cast<BinaryOperator>(Op1)->swapOperands();
4201 std::swap(A, B);
4202 }
4203 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004204 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004205 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004206 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004207 }
4208 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004209 }
4210
Reid Spencere4d87aa2006-12-23 06:05:41 +00004211 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4212 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4213 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004214 return R;
4215
Chris Lattner955f3312004-09-28 21:48:02 +00004216 Value *LHSVal, *RHSVal;
4217 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004218 ICmpInst::Predicate LHSCC, RHSCC;
4219 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4220 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4221 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4222 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4223 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4224 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4225 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00004226 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4227
4228 // Don't try to fold ICMP_SLT + ICMP_ULT.
4229 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4230 ICmpInst::isSignedPredicate(LHSCC) ==
4231 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00004232 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00004233 ICmpInst::Predicate GT;
4234 if (ICmpInst::isSignedPredicate(LHSCC) ||
4235 (ICmpInst::isEquality(LHSCC) &&
4236 ICmpInst::isSignedPredicate(RHSCC)))
4237 GT = ICmpInst::ICMP_SGT;
4238 else
4239 GT = ICmpInst::ICMP_UGT;
4240
Reid Spencere4d87aa2006-12-23 06:05:41 +00004241 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4242 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00004243 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00004244 std::swap(LHS, RHS);
4245 std::swap(LHSCst, RHSCst);
4246 std::swap(LHSCC, RHSCC);
4247 }
4248
Reid Spencere4d87aa2006-12-23 06:05:41 +00004249 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00004250 // comparing a value against two constants and and'ing the result
4251 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004252 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4253 // (from the FoldICmpLogical check above), that the two constants
4254 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00004255 assert(LHSCst != RHSCst && "Compares not folded above?");
4256
4257 switch (LHSCC) {
4258 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004259 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00004260 switch (RHSCC) {
4261 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004262 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4263 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4264 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004265 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004266 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4267 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4268 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00004269 return ReplaceInstUsesWith(I, LHS);
4270 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004271 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00004272 switch (RHSCC) {
4273 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004274 case ICmpInst::ICMP_ULT:
4275 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4276 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4277 break; // (X != 13 & X u< 15) -> no change
4278 case ICmpInst::ICMP_SLT:
4279 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4280 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4281 break; // (X != 13 & X s< 15) -> no change
4282 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4283 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4284 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004285 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004286 case ICmpInst::ICMP_NE:
4287 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004288 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004289 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004290 LHSVal->getName()+".off");
4291 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004292 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4293 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004294 }
4295 break; // (X != 13 & X != 15) -> no change
4296 }
4297 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004298 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004299 switch (RHSCC) {
4300 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004301 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4302 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004303 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004304 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4305 break;
4306 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4307 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004308 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004309 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4310 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004311 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004312 break;
4313 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004314 switch (RHSCC) {
4315 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004316 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4317 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004318 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004319 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4320 break;
4321 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4322 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004323 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004324 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4325 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004326 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004327 break;
4328 case ICmpInst::ICMP_UGT:
4329 switch (RHSCC) {
4330 default: assert(0 && "Unknown integer condition code!");
4331 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4332 return ReplaceInstUsesWith(I, LHS);
4333 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4334 return ReplaceInstUsesWith(I, RHS);
4335 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4336 break;
4337 case ICmpInst::ICMP_NE:
4338 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4339 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4340 break; // (X u> 13 & X != 15) -> no change
4341 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4342 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4343 true, I);
4344 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4345 break;
4346 }
4347 break;
4348 case ICmpInst::ICMP_SGT:
4349 switch (RHSCC) {
4350 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004351 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004352 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4353 return ReplaceInstUsesWith(I, RHS);
4354 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4355 break;
4356 case ICmpInst::ICMP_NE:
4357 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4358 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4359 break; // (X s> 13 & X != 15) -> no change
4360 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4361 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4362 true, I);
4363 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4364 break;
4365 }
4366 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004367 }
4368 }
4369 }
4370
Chris Lattner6fc205f2006-05-05 06:39:07 +00004371 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004372 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4373 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4374 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4375 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004376 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004377 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004378 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4379 I.getType(), TD) &&
4380 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4381 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004382 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004383 Op1C->getOperand(0),
4384 I.getName());
4385 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004386 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004387 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004388 }
Chris Lattnere511b742006-11-14 07:46:50 +00004389
4390 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004391 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4392 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4393 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004394 SI0->getOperand(1) == SI1->getOperand(1) &&
4395 (SI0->hasOneUse() || SI1->hasOneUse())) {
4396 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004397 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004398 SI1->getOperand(0),
4399 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004400 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004401 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004402 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004403 }
4404
Chris Lattner99c65742007-10-24 05:38:08 +00004405 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4406 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4407 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4408 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4409 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4410 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4411 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4412 // If either of the constants are nans, then the whole thing returns
4413 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004414 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004415 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4416 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4417 RHS->getOperand(0));
4418 }
4419 }
4420 }
4421
Chris Lattner7e708292002-06-25 16:13:24 +00004422 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004423}
4424
Chris Lattnerafe91a52006-06-15 19:07:26 +00004425/// CollectBSwapParts - Look to see if the specified value defines a single byte
4426/// in the result. If it does, and if the specified byte hasn't been filled in
4427/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004428static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004429 Instruction *I = dyn_cast<Instruction>(V);
4430 if (I == 0) return true;
4431
4432 // If this is an or instruction, it is an inner node of the bswap.
4433 if (I->getOpcode() == Instruction::Or)
4434 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4435 CollectBSwapParts(I->getOperand(1), ByteValues);
4436
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004437 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004438 // If this is a shift by a constant int, and it is "24", then its operand
4439 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004440 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004441 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004442 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004443 8*(ByteValues.size()-1))
4444 return true;
4445
4446 unsigned DestNo;
4447 if (I->getOpcode() == Instruction::Shl) {
4448 // X << 24 defines the top byte with the lowest of the input bytes.
4449 DestNo = ByteValues.size()-1;
4450 } else {
4451 // X >>u 24 defines the low byte with the highest of the input bytes.
4452 DestNo = 0;
4453 }
4454
4455 // If the destination byte value is already defined, the values are or'd
4456 // together, which isn't a bswap (unless it's an or of the same bits).
4457 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4458 return true;
4459 ByteValues[DestNo] = I->getOperand(0);
4460 return false;
4461 }
4462
4463 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4464 // don't have this.
4465 Value *Shift = 0, *ShiftLHS = 0;
4466 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4467 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4468 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4469 return true;
4470 Instruction *SI = cast<Instruction>(Shift);
4471
4472 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004473 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4474 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004475 return true;
4476
4477 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4478 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004479 if (AndAmt->getValue().getActiveBits() > 64)
4480 return true;
4481 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004482 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004483 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004484 break;
4485 // Unknown mask for bswap.
4486 if (DestByte == ByteValues.size()) return true;
4487
Reid Spencerb83eb642006-10-20 07:07:24 +00004488 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004489 unsigned SrcByte;
4490 if (SI->getOpcode() == Instruction::Shl)
4491 SrcByte = DestByte - ShiftBytes;
4492 else
4493 SrcByte = DestByte + ShiftBytes;
4494
4495 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4496 if (SrcByte != ByteValues.size()-DestByte-1)
4497 return true;
4498
4499 // If the destination byte value is already defined, the values are or'd
4500 // together, which isn't a bswap (unless it's an or of the same bits).
4501 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4502 return true;
4503 ByteValues[DestByte] = SI->getOperand(0);
4504 return false;
4505}
4506
4507/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4508/// If so, insert the new bswap intrinsic and return it.
4509Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004510 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4511 if (!ITy || ITy->getBitWidth() % 16)
4512 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004513
4514 /// ByteValues - For each byte of the result, we keep track of which value
4515 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004516 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004517 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004518
4519 // Try to find all the pieces corresponding to the bswap.
4520 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4521 CollectBSwapParts(I.getOperand(1), ByteValues))
4522 return 0;
4523
4524 // Check to see if all of the bytes come from the same value.
4525 Value *V = ByteValues[0];
4526 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4527
4528 // Check to make sure that all of the bytes come from the same value.
4529 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4530 if (ByteValues[i] != V)
4531 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004532 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004533 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004534 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004535 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004536}
4537
4538
Chris Lattner7e708292002-06-25 16:13:24 +00004539Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004540 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004541 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004542
Chris Lattner42593e62007-03-24 23:56:43 +00004543 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004544 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004545
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004546 // or X, X = X
4547 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004548 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004549
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004550 // See if we can simplify any instructions used by the instruction whose sole
4551 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004552 if (!isa<VectorType>(I.getType())) {
4553 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4554 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4555 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4556 KnownZero, KnownOne))
4557 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004558 } else if (isa<ConstantAggregateZero>(Op1)) {
4559 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4560 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4561 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4562 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004563 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004564
4565
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004566
Chris Lattner3f5b8772002-05-06 16:14:14 +00004567 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004568 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004569 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004570 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4571 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004572 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004573 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004574 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004575 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004576 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004577 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004578
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004579 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4580 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004581 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004582 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004583 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004584 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004585 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004586 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004587
4588 // Try to fold constant and into select arguments.
4589 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004590 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004591 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004592 if (isa<PHINode>(Op0))
4593 if (Instruction *NV = FoldOpIntoPhi(I))
4594 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004595 }
4596
Chris Lattner4f637d42006-01-06 17:59:59 +00004597 Value *A = 0, *B = 0;
4598 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004599
4600 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4601 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4602 return ReplaceInstUsesWith(I, Op1);
4603 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4604 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4605 return ReplaceInstUsesWith(I, Op0);
4606
Chris Lattner6423d4c2006-07-10 20:25:24 +00004607 // (A | B) | C and A | (B | C) -> bswap if possible.
4608 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004609 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004610 match(Op1, m_Or(m_Value(), m_Value())) ||
4611 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4612 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004613 if (Instruction *BSwap = MatchBSwap(I))
4614 return BSwap;
4615 }
4616
Chris Lattner6e4c6492005-05-09 04:58:36 +00004617 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4618 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004619 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004620 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004621 InsertNewInstBefore(NOr, I);
4622 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004623 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004624 }
4625
4626 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4627 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004628 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004629 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004630 InsertNewInstBefore(NOr, I);
4631 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004632 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004633 }
4634
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004635 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004636 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004637 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4638 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004639 Value *V1 = 0, *V2 = 0, *V3 = 0;
4640 C1 = dyn_cast<ConstantInt>(C);
4641 C2 = dyn_cast<ConstantInt>(D);
4642 if (C1 && C2) { // (A & C1)|(B & C2)
4643 // If we have: ((V + N) & C1) | (V & C2)
4644 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4645 // replace with V+N.
4646 if (C1->getValue() == ~C2->getValue()) {
4647 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4648 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4649 // Add commutes, try both ways.
4650 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4651 return ReplaceInstUsesWith(I, A);
4652 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4653 return ReplaceInstUsesWith(I, A);
4654 }
4655 // Or commutes, try both ways.
4656 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4657 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4658 // Add commutes, try both ways.
4659 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4660 return ReplaceInstUsesWith(I, B);
4661 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4662 return ReplaceInstUsesWith(I, B);
4663 }
4664 }
Chris Lattner044e5332007-04-08 08:01:49 +00004665 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004666 }
4667
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004668 // Check to see if we have any common things being and'ed. If so, find the
4669 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004670 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4671 if (A == B) // (A & C)|(A & D) == A & (C|D)
4672 V1 = A, V2 = C, V3 = D;
4673 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4674 V1 = A, V2 = B, V3 = C;
4675 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4676 V1 = C, V2 = A, V3 = D;
4677 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4678 V1 = C, V2 = A, V3 = B;
4679
4680 if (V1) {
4681 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004682 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4683 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004684 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004685 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004686 }
Chris Lattnere511b742006-11-14 07:46:50 +00004687
4688 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004689 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4690 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4691 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004692 SI0->getOperand(1) == SI1->getOperand(1) &&
4693 (SI0->hasOneUse() || SI1->hasOneUse())) {
4694 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004695 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004696 SI1->getOperand(0),
4697 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004698 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004699 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004700 }
4701 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004702
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004703 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4704 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004705 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004706 } else {
4707 A = 0;
4708 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004709 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004710 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4711 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004712 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004713
Misha Brukmancb6267b2004-07-30 12:50:08 +00004714 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004715 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004716 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004717 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004718 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004719 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004720 }
Chris Lattnera2881962003-02-18 19:28:33 +00004721
Reid Spencere4d87aa2006-12-23 06:05:41 +00004722 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4723 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4724 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004725 return R;
4726
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004727 Value *LHSVal, *RHSVal;
4728 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004729 ICmpInst::Predicate LHSCC, RHSCC;
4730 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4731 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4732 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4733 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4734 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4735 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4736 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004737 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4738 // We can't fold (ugt x, C) | (sgt x, C2).
4739 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004740 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004741 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004742 bool NeedsSwap;
4743 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004744 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004745 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004746 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004747
4748 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004749 std::swap(LHS, RHS);
4750 std::swap(LHSCst, RHSCst);
4751 std::swap(LHSCC, RHSCC);
4752 }
4753
Reid Spencere4d87aa2006-12-23 06:05:41 +00004754 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004755 // comparing a value against two constants and or'ing the result
4756 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004757 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4758 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004759 // equal.
4760 assert(LHSCst != RHSCst && "Compares not folded above?");
4761
4762 switch (LHSCC) {
4763 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004764 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004765 switch (RHSCC) {
4766 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004767 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004768 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4769 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004770 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004771 LHSVal->getName()+".off");
4772 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004773 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004774 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004775 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004776 break; // (X == 13 | X == 15) -> no change
4777 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4778 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004779 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004780 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4781 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4782 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004783 return ReplaceInstUsesWith(I, RHS);
4784 }
4785 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004786 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004787 switch (RHSCC) {
4788 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004789 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4790 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4791 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004792 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004793 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4794 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4795 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004796 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004797 }
4798 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004799 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004800 switch (RHSCC) {
4801 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004802 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004803 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004804 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004805 // If RHSCst is [us]MAXINT, it is always false. Not handling
4806 // this can cause overflow.
4807 if (RHSCst->isMaxValue(false))
4808 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004809 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4810 false, I);
4811 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4812 break;
4813 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4814 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004815 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004816 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4817 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004818 }
4819 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004820 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004821 switch (RHSCC) {
4822 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004823 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4824 break;
4825 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004826 // If RHSCst is [us]MAXINT, it is always false. Not handling
4827 // this can cause overflow.
4828 if (RHSCst->isMaxValue(true))
4829 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004830 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4831 false, I);
4832 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4833 break;
4834 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4835 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4836 return ReplaceInstUsesWith(I, RHS);
4837 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4838 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004839 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004840 break;
4841 case ICmpInst::ICMP_UGT:
4842 switch (RHSCC) {
4843 default: assert(0 && "Unknown integer condition code!");
4844 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4845 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4846 return ReplaceInstUsesWith(I, LHS);
4847 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4848 break;
4849 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4850 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004851 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004852 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4853 break;
4854 }
4855 break;
4856 case ICmpInst::ICMP_SGT:
4857 switch (RHSCC) {
4858 default: assert(0 && "Unknown integer condition code!");
4859 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4860 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4861 return ReplaceInstUsesWith(I, LHS);
4862 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4863 break;
4864 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4865 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004866 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004867 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4868 break;
4869 }
4870 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004871 }
4872 }
4873 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004874
4875 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004876 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004877 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004878 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004879 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4880 !isa<ICmpInst>(Op1C->getOperand(0))) {
4881 const Type *SrcTy = Op0C->getOperand(0)->getType();
4882 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4883 // Only do this if the casts both really cause code to be
4884 // generated.
4885 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4886 I.getType(), TD) &&
4887 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4888 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004889 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004890 Op1C->getOperand(0),
4891 I.getName());
4892 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004893 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004894 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004895 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004896 }
Chris Lattner99c65742007-10-24 05:38:08 +00004897 }
4898
4899
4900 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4901 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4902 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4903 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004904 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4905 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004906 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4907 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4908 // If either of the constants are nans, then the whole thing returns
4909 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004910 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004911 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4912
4913 // Otherwise, no need to compare the two constants, compare the
4914 // rest.
4915 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4916 RHS->getOperand(0));
4917 }
4918 }
4919 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004920
Chris Lattner7e708292002-06-25 16:13:24 +00004921 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004922}
4923
Dan Gohman844731a2008-05-13 00:00:25 +00004924namespace {
4925
Chris Lattnerc317d392004-02-16 01:20:27 +00004926// XorSelf - Implements: X ^ X --> 0
4927struct XorSelf {
4928 Value *RHS;
4929 XorSelf(Value *rhs) : RHS(rhs) {}
4930 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4931 Instruction *apply(BinaryOperator &Xor) const {
4932 return &Xor;
4933 }
4934};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004935
Dan Gohman844731a2008-05-13 00:00:25 +00004936}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004937
Chris Lattner7e708292002-06-25 16:13:24 +00004938Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004939 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004940 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004941
Evan Chengd34af782008-03-25 20:07:13 +00004942 if (isa<UndefValue>(Op1)) {
4943 if (isa<UndefValue>(Op0))
4944 // Handle undef ^ undef -> 0 special case. This is a common
4945 // idiom (misuse).
4946 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004947 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004948 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004949
Chris Lattnerc317d392004-02-16 01:20:27 +00004950 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4951 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004952 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004953 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004954 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004955
4956 // See if we can simplify any instructions used by the instruction whose sole
4957 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004958 if (!isa<VectorType>(I.getType())) {
4959 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4960 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4961 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4962 KnownZero, KnownOne))
4963 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004964 } else if (isa<ConstantAggregateZero>(Op1)) {
4965 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004966 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004967
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004968 // Is this a ~ operation?
4969 if (Value *NotOp = dyn_castNotVal(&I)) {
4970 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4971 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4972 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4973 if (Op0I->getOpcode() == Instruction::And ||
4974 Op0I->getOpcode() == Instruction::Or) {
4975 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4976 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4977 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004978 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004979 Op0I->getOperand(1)->getName()+".not");
4980 InsertNewInstBefore(NotY, I);
4981 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004982 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004983 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004984 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004985 }
4986 }
4987 }
4988 }
4989
4990
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004991 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004992 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4993 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4994 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004995 return new ICmpInst(ICI->getInversePredicate(),
4996 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004997
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004998 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4999 return new FCmpInst(FCI->getInversePredicate(),
5000 FCI->getOperand(0), FCI->getOperand(1));
5001 }
5002
Reid Spencere4d87aa2006-12-23 06:05:41 +00005003 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005004 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005005 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5006 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00005007 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5008 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005009 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005010 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005011 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005012
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005013 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005014 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005015 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005016 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00005017 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005018 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00005019 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005020 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00005021 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005022 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005023 // (X + C) ^ signbit -> (X + C + signbit)
5024 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005025 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005026
Chris Lattner7c4049c2004-01-12 19:35:11 +00005027 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005028 } else if (Op0I->getOpcode() == Instruction::Or) {
5029 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005030 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00005031 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5032 // Anything in both C1 and C2 is known to be zero, remove it from
5033 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005034 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005035 NewRHS = ConstantExpr::getAnd(NewRHS,
5036 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005037 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005038 I.setOperand(0, Op0I->getOperand(0));
5039 I.setOperand(1, NewRHS);
5040 return &I;
5041 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005042 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005043 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005044 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005045
5046 // Try to fold constant and into select arguments.
5047 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005048 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005049 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005050 if (isa<PHINode>(Op0))
5051 if (Instruction *NV = FoldOpIntoPhi(I))
5052 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005053 }
5054
Chris Lattner8d969642003-03-10 23:06:50 +00005055 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005056 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005057 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005058
Chris Lattner8d969642003-03-10 23:06:50 +00005059 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005060 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005061 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005062
Chris Lattner318bf792007-03-18 22:51:34 +00005063
5064 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5065 if (Op1I) {
5066 Value *A, *B;
5067 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5068 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005069 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005070 I.swapOperands();
5071 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005072 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005073 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005074 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005075 }
Chris Lattner318bf792007-03-18 22:51:34 +00005076 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5077 if (Op0 == A) // A^(A^B) == B
5078 return ReplaceInstUsesWith(I, B);
5079 else if (Op0 == B) // A^(B^A) == B
5080 return ReplaceInstUsesWith(I, A);
5081 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005082 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005083 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005084 std::swap(A, B);
5085 }
Chris Lattner318bf792007-03-18 22:51:34 +00005086 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005087 I.swapOperands(); // Simplified below.
5088 std::swap(Op0, Op1);
5089 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005090 }
Chris Lattner318bf792007-03-18 22:51:34 +00005091 }
5092
5093 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5094 if (Op0I) {
5095 Value *A, *B;
5096 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5097 if (A == Op1) // (B|A)^B == (A|B)^B
5098 std::swap(A, B);
5099 if (B == Op1) { // (A|B)^B == A & ~B
5100 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005101 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5102 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005103 }
Chris Lattner318bf792007-03-18 22:51:34 +00005104 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5105 if (Op1 == A) // (A^B)^A == B
5106 return ReplaceInstUsesWith(I, B);
5107 else if (Op1 == B) // (B^A)^A == B
5108 return ReplaceInstUsesWith(I, A);
5109 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5110 if (A == Op1) // (A&B)^A -> (B&A)^A
5111 std::swap(A, B);
5112 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005113 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005114 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005115 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5116 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005117 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005118 }
Chris Lattner318bf792007-03-18 22:51:34 +00005119 }
5120
5121 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5122 if (Op0I && Op1I && Op0I->isShift() &&
5123 Op0I->getOpcode() == Op1I->getOpcode() &&
5124 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5125 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5126 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005127 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005128 Op1I->getOperand(0),
5129 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005130 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005131 Op1I->getOperand(1));
5132 }
5133
5134 if (Op0I && Op1I) {
5135 Value *A, *B, *C, *D;
5136 // (A & B)^(A | B) -> A ^ B
5137 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5138 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5139 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005140 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005141 }
5142 // (A | B)^(A & B) -> A ^ B
5143 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5144 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5145 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005146 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005147 }
5148
5149 // (A & B)^(C & D)
5150 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5151 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5152 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5153 // (X & Y)^(X & Y) -> (Y^Z) & X
5154 Value *X = 0, *Y = 0, *Z = 0;
5155 if (A == C)
5156 X = A, Y = B, Z = D;
5157 else if (A == D)
5158 X = A, Y = B, Z = C;
5159 else if (B == C)
5160 X = B, Y = A, Z = D;
5161 else if (B == D)
5162 X = B, Y = A, Z = C;
5163
5164 if (X) {
5165 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005166 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5167 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005168 }
5169 }
5170 }
5171
Reid Spencere4d87aa2006-12-23 06:05:41 +00005172 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5173 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5174 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005175 return R;
5176
Chris Lattner6fc205f2006-05-05 06:39:07 +00005177 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005178 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005179 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005180 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5181 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005182 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005183 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005184 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5185 I.getType(), TD) &&
5186 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5187 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005188 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005189 Op1C->getOperand(0),
5190 I.getName());
5191 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005192 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005193 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005194 }
Chris Lattner99c65742007-10-24 05:38:08 +00005195 }
Chris Lattner7e708292002-06-25 16:13:24 +00005196 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005197}
5198
Chris Lattnera96879a2004-09-29 17:40:11 +00005199/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5200/// overflowed for this type.
5201static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005202 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005203 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005204
Reid Spencere4e40032007-03-21 23:19:50 +00005205 if (IsSigned)
5206 if (In2->getValue().isNegative())
5207 return Result->getValue().sgt(In1->getValue());
5208 else
5209 return Result->getValue().slt(In1->getValue());
5210 else
5211 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005212}
5213
Chris Lattner574da9b2005-01-13 20:14:25 +00005214/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5215/// code necessary to compute the offset from the base pointer (without adding
5216/// in the base pointer). Return the result as a signed integer of intptr size.
5217static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5218 TargetData &TD = IC.getTargetData();
5219 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005220 const Type *IntPtrTy = TD.getIntPtrType();
5221 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005222
5223 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005224 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005225 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005226
Chris Lattner574da9b2005-01-13 20:14:25 +00005227 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5228 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00005229 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005230 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5231 if (OpC->isZero()) continue;
5232
5233 // Handle a struct index, which adds its field offset to the pointer.
5234 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5235 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5236
5237 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5238 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005239 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005240 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005241 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005242 ConstantInt::get(IntPtrTy, Size),
5243 GEP->getName()+".offs"), I);
5244 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005245 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005246
5247 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5248 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5249 Scale = ConstantExpr::getMul(OC, Scale);
5250 if (Constant *RC = dyn_cast<Constant>(Result))
5251 Result = ConstantExpr::getAdd(RC, Scale);
5252 else {
5253 // Emit an add instruction.
5254 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005255 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005256 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005257 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005258 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005259 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005260 // Convert to correct type.
5261 if (Op->getType() != IntPtrTy) {
5262 if (Constant *OpC = dyn_cast<Constant>(Op))
5263 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5264 else
5265 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5266 Op->getName()+".c"), I);
5267 }
5268 if (Size != 1) {
5269 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5270 if (Constant *OpC = dyn_cast<Constant>(Op))
5271 Op = ConstantExpr::getMul(OpC, Scale);
5272 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005273 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005274 GEP->getName()+".idx"), I);
5275 }
5276
5277 // Emit an add instruction.
5278 if (isa<Constant>(Op) && isa<Constant>(Result))
5279 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5280 cast<Constant>(Result));
5281 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005282 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005283 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005284 }
5285 return Result;
5286}
5287
Chris Lattner10c0d912008-04-22 02:53:33 +00005288
5289/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5290/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5291/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5292/// complex, and scales are involved. The above expression would also be legal
5293/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5294/// later form is less amenable to optimization though, and we are allowed to
5295/// generate the first by knowing that pointer arithmetic doesn't overflow.
5296///
5297/// If we can't emit an optimized form for this expression, this returns null.
5298///
5299static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5300 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005301 TargetData &TD = IC.getTargetData();
5302 gep_type_iterator GTI = gep_type_begin(GEP);
5303
5304 // Check to see if this gep only has a single variable index. If so, and if
5305 // any constant indices are a multiple of its scale, then we can compute this
5306 // in terms of the scale of the variable index. For example, if the GEP
5307 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5308 // because the expression will cross zero at the same point.
5309 unsigned i, e = GEP->getNumOperands();
5310 int64_t Offset = 0;
5311 for (i = 1; i != e; ++i, ++GTI) {
5312 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5313 // Compute the aggregate offset of constant indices.
5314 if (CI->isZero()) continue;
5315
5316 // Handle a struct index, which adds its field offset to the pointer.
5317 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5318 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5319 } else {
5320 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5321 Offset += Size*CI->getSExtValue();
5322 }
5323 } else {
5324 // Found our variable index.
5325 break;
5326 }
5327 }
5328
5329 // If there are no variable indices, we must have a constant offset, just
5330 // evaluate it the general way.
5331 if (i == e) return 0;
5332
5333 Value *VariableIdx = GEP->getOperand(i);
5334 // Determine the scale factor of the variable element. For example, this is
5335 // 4 if the variable index is into an array of i32.
5336 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5337
5338 // Verify that there are no other variable indices. If so, emit the hard way.
5339 for (++i, ++GTI; i != e; ++i, ++GTI) {
5340 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5341 if (!CI) return 0;
5342
5343 // Compute the aggregate offset of constant indices.
5344 if (CI->isZero()) continue;
5345
5346 // Handle a struct index, which adds its field offset to the pointer.
5347 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5348 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5349 } else {
5350 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5351 Offset += Size*CI->getSExtValue();
5352 }
5353 }
5354
5355 // Okay, we know we have a single variable index, which must be a
5356 // pointer/array/vector index. If there is no offset, life is simple, return
5357 // the index.
5358 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5359 if (Offset == 0) {
5360 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5361 // we don't need to bother extending: the extension won't affect where the
5362 // computation crosses zero.
5363 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5364 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5365 VariableIdx->getNameStart(), &I);
5366 return VariableIdx;
5367 }
5368
5369 // Otherwise, there is an index. The computation we will do will be modulo
5370 // the pointer size, so get it.
5371 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5372
5373 Offset &= PtrSizeMask;
5374 VariableScale &= PtrSizeMask;
5375
5376 // To do this transformation, any constant index must be a multiple of the
5377 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5378 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5379 // multiple of the variable scale.
5380 int64_t NewOffs = Offset / (int64_t)VariableScale;
5381 if (Offset != NewOffs*(int64_t)VariableScale)
5382 return 0;
5383
5384 // Okay, we can do this evaluation. Start by converting the index to intptr.
5385 const Type *IntPtrTy = TD.getIntPtrType();
5386 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005387 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005388 true /*SExt*/,
5389 VariableIdx->getNameStart(), &I);
5390 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005391 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005392}
5393
5394
Reid Spencere4d87aa2006-12-23 06:05:41 +00005395/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005396/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005397Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5398 ICmpInst::Predicate Cond,
5399 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005400 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005401
Chris Lattner10c0d912008-04-22 02:53:33 +00005402 // Look through bitcasts.
5403 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5404 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005405
Chris Lattner574da9b2005-01-13 20:14:25 +00005406 Value *PtrBase = GEPLHS->getOperand(0);
5407 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005408 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005409 // This transformation (ignoring the base and scales) is valid because we
5410 // know pointers can't overflow. See if we can output an optimized form.
5411 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5412
5413 // If not, synthesize the offset the hard way.
5414 if (Offset == 0)
5415 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005416 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5417 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005418 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005419 // If the base pointers are different, but the indices are the same, just
5420 // compare the base pointer.
5421 if (PtrBase != GEPRHS->getOperand(0)) {
5422 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005423 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005424 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005425 if (IndicesTheSame)
5426 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5427 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5428 IndicesTheSame = false;
5429 break;
5430 }
5431
5432 // If all indices are the same, just compare the base pointers.
5433 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005434 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5435 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005436
5437 // Otherwise, the base pointers are different and the indices are
5438 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005439 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005440 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005441
Chris Lattnere9d782b2005-01-13 22:25:21 +00005442 // If one of the GEPs has all zero indices, recurse.
5443 bool AllZeros = true;
5444 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5445 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5446 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5447 AllZeros = false;
5448 break;
5449 }
5450 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005451 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5452 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005453
5454 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005455 AllZeros = true;
5456 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5457 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5458 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5459 AllZeros = false;
5460 break;
5461 }
5462 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005463 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005464
Chris Lattner4401c9c2005-01-14 00:20:05 +00005465 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5466 // If the GEPs only differ by one index, compare it.
5467 unsigned NumDifferences = 0; // Keep track of # differences.
5468 unsigned DiffOperand = 0; // The operand that differs.
5469 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5470 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005471 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5472 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005473 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005474 NumDifferences = 2;
5475 break;
5476 } else {
5477 if (NumDifferences++) break;
5478 DiffOperand = i;
5479 }
5480 }
5481
5482 if (NumDifferences == 0) // SAME GEP?
5483 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005484 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005485 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005486
Chris Lattner4401c9c2005-01-14 00:20:05 +00005487 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005488 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5489 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005490 // Make sure we do a signed comparison here.
5491 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005492 }
5493 }
5494
Reid Spencere4d87aa2006-12-23 06:05:41 +00005495 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005496 // the result to fold to a constant!
5497 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5498 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5499 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5500 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5501 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005502 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005503 }
5504 }
5505 return 0;
5506}
5507
Chris Lattnera5406232008-05-19 20:18:56 +00005508/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5509///
5510Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5511 Instruction *LHSI,
5512 Constant *RHSC) {
5513 if (!isa<ConstantFP>(RHSC)) return 0;
5514 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5515
5516 // Get the width of the mantissa. We don't want to hack on conversions that
5517 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005518 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005519 if (MantissaWidth == -1) return 0; // Unknown.
5520
5521 // Check to see that the input is converted from an integer type that is small
5522 // enough that preserves all bits. TODO: check here for "known" sign bits.
5523 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5524 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5525
5526 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5527 if (isa<UIToFPInst>(LHSI))
5528 ++InputSize;
5529
5530 // If the conversion would lose info, don't hack on this.
5531 if ((int)InputSize > MantissaWidth)
5532 return 0;
5533
5534 // Otherwise, we can potentially simplify the comparison. We know that it
5535 // will always come through as an integer value and we know the constant is
5536 // not a NAN (it would have been previously simplified).
5537 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5538
5539 ICmpInst::Predicate Pred;
5540 switch (I.getPredicate()) {
5541 default: assert(0 && "Unexpected predicate!");
5542 case FCmpInst::FCMP_UEQ:
5543 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5544 case FCmpInst::FCMP_UGT:
5545 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5546 case FCmpInst::FCMP_UGE:
5547 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5548 case FCmpInst::FCMP_ULT:
5549 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5550 case FCmpInst::FCMP_ULE:
5551 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5552 case FCmpInst::FCMP_UNE:
5553 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5554 case FCmpInst::FCMP_ORD:
5555 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5556 case FCmpInst::FCMP_UNO:
5557 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5558 }
5559
5560 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5561
5562 // Now we know that the APFloat is a normal number, zero or inf.
5563
Chris Lattner85162782008-05-20 03:50:52 +00005564 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005565 // comparing an i8 to 300.0.
5566 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5567
5568 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5569 // and large values.
5570 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5571 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5572 APFloat::rmNearestTiesToEven);
5573 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00005574 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5575 Pred == ICmpInst::ICMP_SLE)
Chris Lattnera5406232008-05-19 20:18:56 +00005576 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5577 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5578 }
5579
5580 // See if the RHS value is < SignedMin.
5581 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5582 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5583 APFloat::rmNearestTiesToEven);
5584 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00005585 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5586 Pred == ICmpInst::ICMP_SGE)
Chris Lattnera5406232008-05-19 20:18:56 +00005587 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5588 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5589 }
5590
5591 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5592 // it may still be fractional. See if it is fractional by casting the FP
5593 // value to the integer value and back, checking for equality. Don't do this
5594 // for zero, because -0.0 is not fractional.
5595 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5596 if (!RHS.isZero() &&
5597 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5598 // If we had a comparison against a fractional value, we have to adjust
5599 // the compare predicate and sometimes the value. RHSC is rounded towards
5600 // zero at this point.
5601 switch (Pred) {
5602 default: assert(0 && "Unexpected integer comparison!");
5603 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5604 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5605 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5606 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5607 case ICmpInst::ICMP_SLE:
5608 // (float)int <= 4.4 --> int <= 4
5609 // (float)int <= -4.4 --> int < -4
5610 if (RHS.isNegative())
5611 Pred = ICmpInst::ICMP_SLT;
5612 break;
5613 case ICmpInst::ICMP_SLT:
5614 // (float)int < -4.4 --> int < -4
5615 // (float)int < 4.4 --> int <= 4
5616 if (!RHS.isNegative())
5617 Pred = ICmpInst::ICMP_SLE;
5618 break;
5619 case ICmpInst::ICMP_SGT:
5620 // (float)int > 4.4 --> int > 4
5621 // (float)int > -4.4 --> int >= -4
5622 if (RHS.isNegative())
5623 Pred = ICmpInst::ICMP_SGE;
5624 break;
5625 case ICmpInst::ICMP_SGE:
5626 // (float)int >= -4.4 --> int >= -4
5627 // (float)int >= 4.4 --> int > 4
5628 if (!RHS.isNegative())
5629 Pred = ICmpInst::ICMP_SGT;
5630 break;
5631 }
5632 }
5633
5634 // Lower this FP comparison into an appropriate integer version of the
5635 // comparison.
5636 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5637}
5638
Reid Spencere4d87aa2006-12-23 06:05:41 +00005639Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5640 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005641 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005642
Chris Lattner58e97462007-01-14 19:42:17 +00005643 // Fold trivial predicates.
5644 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5645 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5646 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5647 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5648
5649 // Simplify 'fcmp pred X, X'
5650 if (Op0 == Op1) {
5651 switch (I.getPredicate()) {
5652 default: assert(0 && "Unknown predicate!");
5653 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5654 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5655 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5656 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5657 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5658 case FCmpInst::FCMP_OLT: // True if ordered and less than
5659 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5660 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5661
5662 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5663 case FCmpInst::FCMP_ULT: // True if unordered or less than
5664 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5665 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5666 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5667 I.setPredicate(FCmpInst::FCMP_UNO);
5668 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5669 return &I;
5670
5671 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5672 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5673 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5674 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5675 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5676 I.setPredicate(FCmpInst::FCMP_ORD);
5677 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5678 return &I;
5679 }
5680 }
5681
Reid Spencere4d87aa2006-12-23 06:05:41 +00005682 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005683 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005684
Reid Spencere4d87aa2006-12-23 06:05:41 +00005685 // Handle fcmp with constant RHS
5686 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005687 // If the constant is a nan, see if we can fold the comparison based on it.
5688 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5689 if (CFP->getValueAPF().isNaN()) {
5690 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5691 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005692 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5693 "Comparison must be either ordered or unordered!");
5694 // True if unordered.
5695 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005696 }
5697 }
5698
Reid Spencere4d87aa2006-12-23 06:05:41 +00005699 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5700 switch (LHSI->getOpcode()) {
5701 case Instruction::PHI:
5702 if (Instruction *NV = FoldOpIntoPhi(I))
5703 return NV;
5704 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005705 case Instruction::SIToFP:
5706 case Instruction::UIToFP:
5707 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5708 return NV;
5709 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005710 case Instruction::Select:
5711 // If either operand of the select is a constant, we can fold the
5712 // comparison into the select arms, which will cause one to be
5713 // constant folded and the select turned into a bitwise or.
5714 Value *Op1 = 0, *Op2 = 0;
5715 if (LHSI->hasOneUse()) {
5716 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5717 // Fold the known value into the constant operand.
5718 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5719 // Insert a new FCmp of the other select operand.
5720 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5721 LHSI->getOperand(2), RHSC,
5722 I.getName()), I);
5723 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5724 // Fold the known value into the constant operand.
5725 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5726 // Insert a new FCmp of the other select operand.
5727 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5728 LHSI->getOperand(1), RHSC,
5729 I.getName()), I);
5730 }
5731 }
5732
5733 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005734 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005735 break;
5736 }
5737 }
5738
5739 return Changed ? &I : 0;
5740}
5741
5742Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5743 bool Changed = SimplifyCompare(I);
5744 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5745 const Type *Ty = Op0->getType();
5746
5747 // icmp X, X
5748 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005749 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005750 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005751
5752 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005753 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005754
Reid Spencere4d87aa2006-12-23 06:05:41 +00005755 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005756 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005757 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5758 isa<ConstantPointerNull>(Op0)) &&
5759 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005760 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005761 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005762 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005763
Reid Spencere4d87aa2006-12-23 06:05:41 +00005764 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005765 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005766 switch (I.getPredicate()) {
5767 default: assert(0 && "Invalid icmp instruction!");
5768 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005769 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005770 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005771 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005772 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005773 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005774 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005775
Reid Spencere4d87aa2006-12-23 06:05:41 +00005776 case ICmpInst::ICMP_UGT:
5777 case ICmpInst::ICMP_SGT:
5778 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005779 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005780 case ICmpInst::ICMP_ULT:
5781 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005782 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005783 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005784 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005785 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005786 case ICmpInst::ICMP_UGE:
5787 case ICmpInst::ICMP_SGE:
5788 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005789 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005790 case ICmpInst::ICMP_ULE:
5791 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005792 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005793 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005794 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005795 }
5796 }
Chris Lattner8b170942002-08-09 23:47:40 +00005797 }
5798
Chris Lattner2be51ae2004-06-09 04:24:29 +00005799 // See if we are doing a comparison between a constant and an instruction that
5800 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005801 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005802 Value *A, *B;
5803
Chris Lattnerb6566012008-01-05 01:18:20 +00005804 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5805 if (I.isEquality() && CI->isNullValue() &&
5806 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5807 // (icmp cond A B) if cond is equality
5808 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005809 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005810
Reid Spencere4d87aa2006-12-23 06:05:41 +00005811 switch (I.getPredicate()) {
5812 default: break;
5813 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5814 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005815 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005816 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5817 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5818 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5819 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005820 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5821 if (CI->isMinValue(true))
5822 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5823 ConstantInt::getAllOnesValue(Op0->getType()));
5824
Reid Spencere4d87aa2006-12-23 06:05:41 +00005825 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005826
Reid Spencere4d87aa2006-12-23 06:05:41 +00005827 case ICmpInst::ICMP_SLT:
5828 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005829 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005830 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5831 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5832 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5833 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5834 break;
5835
5836 case ICmpInst::ICMP_UGT:
5837 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005838 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005839 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5840 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5841 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5842 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005843
5844 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5845 if (CI->isMaxValue(true))
5846 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5847 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005848 break;
5849
5850 case ICmpInst::ICMP_SGT:
5851 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005852 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005853 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5854 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5855 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5856 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5857 break;
5858
5859 case ICmpInst::ICMP_ULE:
5860 if (CI->isMaxValue(false)) // A <=u 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(false)) // A <=u MIN -> A == MIN
5863 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5864 if (isMaxValueMinusOne(CI,false)) // A <=u 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_SLE:
5869 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005870 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005871 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5872 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5873 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5874 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5875 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005876
Reid Spencere4d87aa2006-12-23 06:05:41 +00005877 case ICmpInst::ICMP_UGE:
5878 if (CI->isMinValue(false)) // A >=u 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(false)) // A >=u MAX -> A == MAX
5881 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5882 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5883 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5884 break;
5885
5886 case ICmpInst::ICMP_SGE:
5887 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005888 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005889 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5890 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5891 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5892 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5893 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005894 }
5895
Reid Spencere4d87aa2006-12-23 06:05:41 +00005896 // If we still have a icmp le or icmp ge instruction, turn it into the
5897 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005898 // already been handled above, this requires little checking.
5899 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005900 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005901 default: break;
5902 case ICmpInst::ICMP_ULE:
5903 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5904 case ICmpInst::ICMP_SLE:
5905 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5906 case ICmpInst::ICMP_UGE:
5907 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5908 case ICmpInst::ICMP_SGE:
5909 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005910 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005911
5912 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005913 // in the input. If this comparison is a normal comparison, it demands all
5914 // bits, if it is a sign bit comparison, it only demands the sign bit.
5915
5916 bool UnusedBit;
5917 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5918
Reid Spencer0460fb32007-03-22 20:36:03 +00005919 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5920 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005921 if (SimplifyDemandedBits(Op0,
5922 isSignBit ? APInt::getSignBit(BitWidth)
5923 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005924 KnownZero, KnownOne, 0))
5925 return &I;
5926
5927 // Given the known and unknown bits, compute a range that the LHS could be
5928 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005929 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005930 // Compute the Min, Max and RHS values based on the known bits. For the
5931 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005932 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5933 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005934 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005935 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5936 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005937 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005938 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5939 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005940 }
5941 switch (I.getPredicate()) { // LE/GE have been folded already.
5942 default: assert(0 && "Unknown icmp opcode!");
5943 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005944 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005945 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005946 break;
5947 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005948 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005949 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005950 break;
5951 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005952 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005953 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005954 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005955 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005956 break;
5957 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005958 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005959 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005960 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005961 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005962 break;
5963 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005964 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005965 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005966 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005967 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005968 break;
5969 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005970 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005971 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005972 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005973 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005974 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005975 }
5976 }
5977
Reid Spencere4d87aa2006-12-23 06:05:41 +00005978 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005979 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005980 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005981 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005982 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5983 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005984 }
5985
Chris Lattner01deb9d2007-04-03 17:43:25 +00005986 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005987 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5988 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5989 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005990 case Instruction::GetElementPtr:
5991 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005992 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005993 bool isAllZeros = true;
5994 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5995 if (!isa<Constant>(LHSI->getOperand(i)) ||
5996 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5997 isAllZeros = false;
5998 break;
5999 }
6000 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006001 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00006002 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6003 }
6004 break;
6005
Chris Lattner6970b662005-04-23 15:31:55 +00006006 case Instruction::PHI:
6007 if (Instruction *NV = FoldOpIntoPhi(I))
6008 return NV;
6009 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006010 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006011 // If either operand of the select is a constant, we can fold the
6012 // comparison into the select arms, which will cause one to be
6013 // constant folded and the select turned into a bitwise or.
6014 Value *Op1 = 0, *Op2 = 0;
6015 if (LHSI->hasOneUse()) {
6016 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6017 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006018 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6019 // Insert a new ICmp of the other select operand.
6020 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6021 LHSI->getOperand(2), RHSC,
6022 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006023 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6024 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006025 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6026 // Insert a new ICmp of the other select operand.
6027 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6028 LHSI->getOperand(1), RHSC,
6029 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006030 }
6031 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006032
Chris Lattner6970b662005-04-23 15:31:55 +00006033 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006034 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006035 break;
6036 }
Chris Lattner4802d902007-04-06 18:57:34 +00006037 case Instruction::Malloc:
6038 // If we have (malloc != null), and if the malloc has a single use, we
6039 // can assume it is successful and remove the malloc.
6040 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6041 AddToWorkList(LHSI);
6042 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006043 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006044 }
6045 break;
6046 }
Chris Lattner6970b662005-04-23 15:31:55 +00006047 }
6048
Reid Spencere4d87aa2006-12-23 06:05:41 +00006049 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006050 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006051 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006052 return NI;
6053 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006054 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6055 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006056 return NI;
6057
Reid Spencere4d87aa2006-12-23 06:05:41 +00006058 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006059 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6060 // now.
6061 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6062 if (isa<PointerType>(Op0->getType()) &&
6063 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006064 // We keep moving the cast from the left operand over to the right
6065 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006066 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006067
Chris Lattner57d86372007-01-06 01:45:59 +00006068 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6069 // so eliminate it as well.
6070 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6071 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006072
Chris Lattnerde90b762003-11-03 04:25:02 +00006073 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006074 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006075 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006076 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006077 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006078 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006079 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006080 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006081 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006082 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006083 }
Chris Lattner57d86372007-01-06 01:45:59 +00006084 }
6085
6086 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006087 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006088 // This comes up when you have code like
6089 // int X = A < B;
6090 // if (X) ...
6091 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006092 // with a constant or another cast from the same type.
6093 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006094 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006095 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006096 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006097
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006098 // ~x < ~y --> y < x
6099 { Value *A, *B;
6100 if (match(Op0, m_Not(m_Value(A))) &&
6101 match(Op1, m_Not(m_Value(B))))
6102 return new ICmpInst(I.getPredicate(), B, A);
6103 }
6104
Chris Lattner65b72ba2006-09-18 04:22:48 +00006105 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006106 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006107
6108 // -x == -y --> x == y
6109 if (match(Op0, m_Neg(m_Value(A))) &&
6110 match(Op1, m_Neg(m_Value(B))))
6111 return new ICmpInst(I.getPredicate(), A, B);
6112
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006113 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6114 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6115 Value *OtherVal = A == Op1 ? B : A;
6116 return new ICmpInst(I.getPredicate(), OtherVal,
6117 Constant::getNullValue(A->getType()));
6118 }
6119
6120 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6121 // A^c1 == C^c2 --> A == C^(c1^c2)
6122 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6123 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6124 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006125 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006126 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006127 return new ICmpInst(I.getPredicate(), A,
6128 InsertNewInstBefore(Xor, I));
6129 }
6130
6131 // A^B == A^D -> B == D
6132 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6133 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6134 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6135 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6136 }
6137 }
6138
6139 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6140 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006141 // A == (A^B) -> B == 0
6142 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006143 return new ICmpInst(I.getPredicate(), OtherVal,
6144 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006145 }
6146 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006147 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006148 return new ICmpInst(I.getPredicate(), B,
6149 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006150 }
6151 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006152 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006153 return new ICmpInst(I.getPredicate(), B,
6154 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00006155 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00006156
Chris Lattner9c2328e2006-11-14 06:06:06 +00006157 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6158 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6159 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6160 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6161 Value *X = 0, *Y = 0, *Z = 0;
6162
6163 if (A == C) {
6164 X = B; Y = D; Z = A;
6165 } else if (A == D) {
6166 X = B; Y = C; Z = A;
6167 } else if (B == C) {
6168 X = A; Y = D; Z = B;
6169 } else if (B == D) {
6170 X = A; Y = C; Z = B;
6171 }
6172
6173 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006174 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6175 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006176 I.setOperand(0, Op1);
6177 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6178 return &I;
6179 }
6180 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006181 }
Chris Lattner7e708292002-06-25 16:13:24 +00006182 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006183}
6184
Chris Lattner562ef782007-06-20 23:46:26 +00006185
6186/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6187/// and CmpRHS are both known to be integer constants.
6188Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6189 ConstantInt *DivRHS) {
6190 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6191 const APInt &CmpRHSV = CmpRHS->getValue();
6192
6193 // FIXME: If the operand types don't match the type of the divide
6194 // then don't attempt this transform. The code below doesn't have the
6195 // logic to deal with a signed divide and an unsigned compare (and
6196 // vice versa). This is because (x /s C1) <s C2 produces different
6197 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6198 // (x /u C1) <u C2. Simply casting the operands and result won't
6199 // work. :( The if statement below tests that condition and bails
6200 // if it finds it.
6201 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6202 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6203 return 0;
6204 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006205 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00006206
6207 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6208 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6209 // C2 (CI). By solving for X we can turn this into a range check
6210 // instead of computing a divide.
6211 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6212
6213 // Determine if the product overflows by seeing if the product is
6214 // not equal to the divide. Make sure we do the same kind of divide
6215 // as in the LHS instruction that we're folding.
6216 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6217 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6218
6219 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006220 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006221
Chris Lattner1dbfd482007-06-21 18:11:19 +00006222 // Figure out the interval that is being checked. For example, a comparison
6223 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6224 // Compute this interval based on the constants involved and the signedness of
6225 // the compare/divide. This computes a half-open interval, keeping track of
6226 // whether either value in the interval overflows. After analysis each
6227 // overflow variable is set to 0 if it's corresponding bound variable is valid
6228 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6229 int LoOverflow = 0, HiOverflow = 0;
6230 ConstantInt *LoBound = 0, *HiBound = 0;
6231
6232
Chris Lattner562ef782007-06-20 23:46:26 +00006233 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006234 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006235 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006236 HiOverflow = LoOverflow = ProdOV;
6237 if (!HiOverflow)
6238 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006239 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006240 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006241 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006242 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6243 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006244 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006245 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6246 HiOverflow = LoOverflow = ProdOV;
6247 if (!HiOverflow)
6248 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006249 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006250 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006251 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6252 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00006253 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006254 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006255 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006256 }
Dan Gohman76491272008-02-13 22:09:18 +00006257 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006258 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006259 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006260 LoBound = AddOne(DivRHS);
6261 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006262 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6263 HiOverflow = 1; // [INTMIN+1, overflow)
6264 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6265 }
Dan Gohman76491272008-02-13 22:09:18 +00006266 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006267 // e.g. X/-5 op 3 --> [-19, -14)
6268 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006269 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006270 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00006271 HiBound = AddOne(Prod);
6272 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006273 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006274 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006275 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006276 HiBound = Subtract(Prod, DivRHS);
6277 }
6278
Chris Lattner1dbfd482007-06-21 18:11:19 +00006279 // Dividing by a negative swaps the condition. LT <-> GT
6280 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006281 }
6282
6283 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006284 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006285 default: assert(0 && "Unhandled icmp opcode!");
6286 case ICmpInst::ICMP_EQ:
6287 if (LoOverflow && HiOverflow)
6288 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6289 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006290 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006291 ICmpInst::ICMP_UGE, X, LoBound);
6292 else if (LoOverflow)
6293 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6294 ICmpInst::ICMP_ULT, X, HiBound);
6295 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006296 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006297 case ICmpInst::ICMP_NE:
6298 if (LoOverflow && HiOverflow)
6299 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6300 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006301 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006302 ICmpInst::ICMP_ULT, X, LoBound);
6303 else if (LoOverflow)
6304 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6305 ICmpInst::ICMP_UGE, X, HiBound);
6306 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006307 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006308 case ICmpInst::ICMP_ULT:
6309 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006310 if (LoOverflow == +1) // Low bound is greater than input range.
6311 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6312 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006313 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006314 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006315 case ICmpInst::ICMP_UGT:
6316 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006317 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006318 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006319 else if (HiOverflow == -1) // High bound less than input range.
6320 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6321 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006322 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6323 else
6324 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6325 }
6326}
6327
6328
Chris Lattner01deb9d2007-04-03 17:43:25 +00006329/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6330///
6331Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6332 Instruction *LHSI,
6333 ConstantInt *RHS) {
6334 const APInt &RHSV = RHS->getValue();
6335
6336 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00006337 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006338 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6339 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6340 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006341 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6342 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006343 Value *CompareVal = LHSI->getOperand(0);
6344
6345 // If the sign bit of the XorCST is not set, there is no change to
6346 // the operation, just stop using the Xor.
6347 if (!XorCST->getValue().isNegative()) {
6348 ICI.setOperand(0, CompareVal);
6349 AddToWorkList(LHSI);
6350 return &ICI;
6351 }
6352
6353 // Was the old condition true if the operand is positive?
6354 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6355
6356 // If so, the new one isn't.
6357 isTrueIfPositive ^= true;
6358
6359 if (isTrueIfPositive)
6360 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6361 else
6362 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6363 }
6364 }
6365 break;
6366 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6367 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6368 LHSI->getOperand(0)->hasOneUse()) {
6369 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6370
6371 // If the LHS is an AND of a truncating cast, we can widen the
6372 // and/compare to be the input width without changing the value
6373 // produced, eliminating a cast.
6374 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6375 // We can do this transformation if either the AND constant does not
6376 // have its sign bit set or if it is an equality comparison.
6377 // Extending a relational comparison when we're checking the sign
6378 // bit would not work.
6379 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006380 (ICI.isEquality() ||
6381 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006382 uint32_t BitWidth =
6383 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6384 APInt NewCST = AndCST->getValue();
6385 NewCST.zext(BitWidth);
6386 APInt NewCI = RHSV;
6387 NewCI.zext(BitWidth);
6388 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006389 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006390 ConstantInt::get(NewCST),LHSI->getName());
6391 InsertNewInstBefore(NewAnd, ICI);
6392 return new ICmpInst(ICI.getPredicate(), NewAnd,
6393 ConstantInt::get(NewCI));
6394 }
6395 }
6396
6397 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6398 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6399 // happens a LOT in code produced by the C front-end, for bitfield
6400 // access.
6401 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6402 if (Shift && !Shift->isShift())
6403 Shift = 0;
6404
6405 ConstantInt *ShAmt;
6406 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6407 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6408 const Type *AndTy = AndCST->getType(); // Type of the and.
6409
6410 // We can fold this as long as we can't shift unknown bits
6411 // into the mask. This can only happen with signed shift
6412 // rights, as they sign-extend.
6413 if (ShAmt) {
6414 bool CanFold = Shift->isLogicalShift();
6415 if (!CanFold) {
6416 // To test for the bad case of the signed shr, see if any
6417 // of the bits shifted in could be tested after the mask.
6418 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6419 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6420
6421 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6422 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6423 AndCST->getValue()) == 0)
6424 CanFold = true;
6425 }
6426
6427 if (CanFold) {
6428 Constant *NewCst;
6429 if (Shift->getOpcode() == Instruction::Shl)
6430 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6431 else
6432 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6433
6434 // Check to see if we are shifting out any of the bits being
6435 // compared.
6436 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6437 // If we shifted bits out, the fold is not going to work out.
6438 // As a special case, check to see if this means that the
6439 // result is always true or false now.
6440 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6441 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6442 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6443 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6444 } else {
6445 ICI.setOperand(1, NewCst);
6446 Constant *NewAndCST;
6447 if (Shift->getOpcode() == Instruction::Shl)
6448 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6449 else
6450 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6451 LHSI->setOperand(1, NewAndCST);
6452 LHSI->setOperand(0, Shift->getOperand(0));
6453 AddToWorkList(Shift); // Shift is dead.
6454 AddUsesToWorkList(ICI);
6455 return &ICI;
6456 }
6457 }
6458 }
6459
6460 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6461 // preferable because it allows the C<<Y expression to be hoisted out
6462 // of a loop if Y is invariant and X is not.
6463 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6464 ICI.isEquality() && !Shift->isArithmeticShift() &&
6465 isa<Instruction>(Shift->getOperand(0))) {
6466 // Compute C << Y.
6467 Value *NS;
6468 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006469 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006470 Shift->getOperand(1), "tmp");
6471 } else {
6472 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006473 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006474 Shift->getOperand(1), "tmp");
6475 }
6476 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6477
6478 // Compute X & (C << Y).
6479 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006480 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006481 InsertNewInstBefore(NewAnd, ICI);
6482
6483 ICI.setOperand(0, NewAnd);
6484 return &ICI;
6485 }
6486 }
6487 break;
6488
Chris Lattnera0141b92007-07-15 20:42:37 +00006489 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6490 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6491 if (!ShAmt) break;
6492
6493 uint32_t TypeBits = RHSV.getBitWidth();
6494
6495 // Check that the shift amount is in range. If not, don't perform
6496 // undefined shifts. When the shift is visited it will be
6497 // simplified.
6498 if (ShAmt->uge(TypeBits))
6499 break;
6500
6501 if (ICI.isEquality()) {
6502 // If we are comparing against bits always shifted out, the
6503 // comparison cannot succeed.
6504 Constant *Comp =
6505 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6506 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6507 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6508 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6509 return ReplaceInstUsesWith(ICI, Cst);
6510 }
6511
6512 if (LHSI->hasOneUse()) {
6513 // Otherwise strength reduce the shift into an and.
6514 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6515 Constant *Mask =
6516 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006517
Chris Lattnera0141b92007-07-15 20:42:37 +00006518 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006519 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006520 Mask, LHSI->getName()+".mask");
6521 Value *And = InsertNewInstBefore(AndI, ICI);
6522 return new ICmpInst(ICI.getPredicate(), And,
6523 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006524 }
6525 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006526
6527 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6528 bool TrueIfSigned = false;
6529 if (LHSI->hasOneUse() &&
6530 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6531 // (X << 31) <s 0 --> (X&1) != 0
6532 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6533 (TypeBits-ShAmt->getZExtValue()-1));
6534 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006535 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006536 Mask, LHSI->getName()+".mask");
6537 Value *And = InsertNewInstBefore(AndI, ICI);
6538
6539 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6540 And, Constant::getNullValue(And->getType()));
6541 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006542 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006543 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006544
6545 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006546 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006547 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006548 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006549 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006550
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006551 // Check that the shift amount is in range. If not, don't perform
6552 // undefined shifts. When the shift is visited it will be
6553 // simplified.
6554 uint32_t TypeBits = RHSV.getBitWidth();
6555 if (ShAmt->uge(TypeBits))
6556 break;
6557
6558 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006559
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006560 // If we are comparing against bits always shifted out, the
6561 // comparison cannot succeed.
6562 APInt Comp = RHSV << ShAmtVal;
6563 if (LHSI->getOpcode() == Instruction::LShr)
6564 Comp = Comp.lshr(ShAmtVal);
6565 else
6566 Comp = Comp.ashr(ShAmtVal);
6567
6568 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6569 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6570 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6571 return ReplaceInstUsesWith(ICI, Cst);
6572 }
6573
6574 // Otherwise, check to see if the bits shifted out are known to be zero.
6575 // If so, we can compare against the unshifted value:
6576 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006577 if (LHSI->hasOneUse() &&
6578 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006579 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6580 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6581 ConstantExpr::getShl(RHS, ShAmt));
6582 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006583
Evan Chengf30752c2008-04-23 00:38:06 +00006584 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006585 // Otherwise strength reduce the shift into an and.
6586 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6587 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006588
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006589 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006590 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006591 Mask, LHSI->getName()+".mask");
6592 Value *And = InsertNewInstBefore(AndI, ICI);
6593 return new ICmpInst(ICI.getPredicate(), And,
6594 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006595 }
6596 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006597 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006598
6599 case Instruction::SDiv:
6600 case Instruction::UDiv:
6601 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6602 // Fold this div into the comparison, producing a range check.
6603 // Determine, based on the divide type, what the range is being
6604 // checked. If there is an overflow on the low or high side, remember
6605 // it, otherwise compute the range [low, hi) bounding the new value.
6606 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006607 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6608 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6609 DivRHS))
6610 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006611 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006612
6613 case Instruction::Add:
6614 // Fold: icmp pred (add, X, C1), C2
6615
6616 if (!ICI.isEquality()) {
6617 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6618 if (!LHSC) break;
6619 const APInt &LHSV = LHSC->getValue();
6620
6621 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6622 .subtract(LHSV);
6623
6624 if (ICI.isSignedPredicate()) {
6625 if (CR.getLower().isSignBit()) {
6626 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6627 ConstantInt::get(CR.getUpper()));
6628 } else if (CR.getUpper().isSignBit()) {
6629 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6630 ConstantInt::get(CR.getLower()));
6631 }
6632 } else {
6633 if (CR.getLower().isMinValue()) {
6634 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6635 ConstantInt::get(CR.getUpper()));
6636 } else if (CR.getUpper().isMinValue()) {
6637 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6638 ConstantInt::get(CR.getLower()));
6639 }
6640 }
6641 }
6642 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006643 }
6644
6645 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6646 if (ICI.isEquality()) {
6647 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6648
6649 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6650 // the second operand is a constant, simplify a bit.
6651 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6652 switch (BO->getOpcode()) {
6653 case Instruction::SRem:
6654 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6655 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6656 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6657 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6658 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006659 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006660 BO->getName());
6661 InsertNewInstBefore(NewRem, ICI);
6662 return new ICmpInst(ICI.getPredicate(), NewRem,
6663 Constant::getNullValue(BO->getType()));
6664 }
6665 }
6666 break;
6667 case Instruction::Add:
6668 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6669 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6670 if (BO->hasOneUse())
6671 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6672 Subtract(RHS, BOp1C));
6673 } else if (RHSV == 0) {
6674 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6675 // efficiently invertible, or if the add has just this one use.
6676 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6677
6678 if (Value *NegVal = dyn_castNegVal(BOp1))
6679 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6680 else if (Value *NegVal = dyn_castNegVal(BOp0))
6681 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6682 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006683 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006684 InsertNewInstBefore(Neg, ICI);
6685 Neg->takeName(BO);
6686 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6687 }
6688 }
6689 break;
6690 case Instruction::Xor:
6691 // For the xor case, we can xor two constants together, eliminating
6692 // the explicit xor.
6693 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6694 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6695 ConstantExpr::getXor(RHS, BOC));
6696
6697 // FALLTHROUGH
6698 case Instruction::Sub:
6699 // Replace (([sub|xor] A, B) != 0) with (A != B)
6700 if (RHSV == 0)
6701 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6702 BO->getOperand(1));
6703 break;
6704
6705 case Instruction::Or:
6706 // If bits are being or'd in that are not present in the constant we
6707 // are comparing against, then the comparison could never succeed!
6708 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6709 Constant *NotCI = ConstantExpr::getNot(RHS);
6710 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6711 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6712 isICMP_NE));
6713 }
6714 break;
6715
6716 case Instruction::And:
6717 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6718 // If bits are being compared against that are and'd out, then the
6719 // comparison can never succeed!
6720 if ((RHSV & ~BOC->getValue()) != 0)
6721 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6722 isICMP_NE));
6723
6724 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6725 if (RHS == BOC && RHSV.isPowerOf2())
6726 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6727 ICmpInst::ICMP_NE, LHSI,
6728 Constant::getNullValue(RHS->getType()));
6729
6730 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6731 if (isSignBit(BOC)) {
6732 Value *X = BO->getOperand(0);
6733 Constant *Zero = Constant::getNullValue(X->getType());
6734 ICmpInst::Predicate pred = isICMP_NE ?
6735 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6736 return new ICmpInst(pred, X, Zero);
6737 }
6738
6739 // ((X & ~7) == 0) --> X < 8
6740 if (RHSV == 0 && isHighOnes(BOC)) {
6741 Value *X = BO->getOperand(0);
6742 Constant *NegX = ConstantExpr::getNeg(BOC);
6743 ICmpInst::Predicate pred = isICMP_NE ?
6744 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6745 return new ICmpInst(pred, X, NegX);
6746 }
6747 }
6748 default: break;
6749 }
6750 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6751 // Handle icmp {eq|ne} <intrinsic>, intcst.
6752 if (II->getIntrinsicID() == Intrinsic::bswap) {
6753 AddToWorkList(II);
6754 ICI.setOperand(0, II->getOperand(1));
6755 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6756 return &ICI;
6757 }
6758 }
6759 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006760 // If the LHS is a cast from an integral value of the same size,
6761 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006762 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6763 Value *CastOp = Cast->getOperand(0);
6764 const Type *SrcTy = CastOp->getType();
6765 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6766 if (SrcTy->isInteger() &&
6767 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6768 // If this is an unsigned comparison, try to make the comparison use
6769 // smaller constant values.
6770 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6771 // X u< 128 => X s> -1
6772 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6773 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6774 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6775 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6776 // X u> 127 => X s< 0
6777 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6778 Constant::getNullValue(SrcTy));
6779 }
6780 }
6781 }
6782 }
6783 return 0;
6784}
6785
6786/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6787/// We only handle extending casts so far.
6788///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006789Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6790 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006791 Value *LHSCIOp = LHSCI->getOperand(0);
6792 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006793 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006794 Value *RHSCIOp;
6795
Chris Lattner8c756c12007-05-05 22:41:33 +00006796 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6797 // integer type is the same size as the pointer type.
6798 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6799 getTargetData().getPointerSizeInBits() ==
6800 cast<IntegerType>(DestTy)->getBitWidth()) {
6801 Value *RHSOp = 0;
6802 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006803 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006804 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6805 RHSOp = RHSC->getOperand(0);
6806 // If the pointer types don't match, insert a bitcast.
6807 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006808 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006809 }
6810
6811 if (RHSOp)
6812 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6813 }
6814
6815 // The code below only handles extension cast instructions, so far.
6816 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006817 if (LHSCI->getOpcode() != Instruction::ZExt &&
6818 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006819 return 0;
6820
Reid Spencere4d87aa2006-12-23 06:05:41 +00006821 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6822 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006823
Reid Spencere4d87aa2006-12-23 06:05:41 +00006824 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006825 // Not an extension from the same type?
6826 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006827 if (RHSCIOp->getType() != LHSCIOp->getType())
6828 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006829
Nick Lewycky4189a532008-01-28 03:48:02 +00006830 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006831 // and the other is a zext), then we can't handle this.
6832 if (CI->getOpcode() != LHSCI->getOpcode())
6833 return 0;
6834
Nick Lewycky4189a532008-01-28 03:48:02 +00006835 // Deal with equality cases early.
6836 if (ICI.isEquality())
6837 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6838
6839 // A signed comparison of sign extended values simplifies into a
6840 // signed comparison.
6841 if (isSignedCmp && isSignedExt)
6842 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6843
6844 // The other three cases all fold into an unsigned comparison.
6845 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006846 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006847
Reid Spencere4d87aa2006-12-23 06:05:41 +00006848 // If we aren't dealing with a constant on the RHS, exit early
6849 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6850 if (!CI)
6851 return 0;
6852
6853 // Compute the constant that would happen if we truncated to SrcTy then
6854 // reextended to DestTy.
6855 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6856 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6857
6858 // If the re-extended constant didn't change...
6859 if (Res2 == CI) {
6860 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6861 // For example, we might have:
6862 // %A = sext short %X to uint
6863 // %B = icmp ugt uint %A, 1330
6864 // It is incorrect to transform this into
6865 // %B = icmp ugt short %X, 1330
6866 // because %A may have negative value.
6867 //
6868 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6869 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006870 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006871 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6872 else
6873 return 0;
6874 }
6875
6876 // The re-extended constant changed so the constant cannot be represented
6877 // in the shorter type. Consequently, we cannot emit a simple comparison.
6878
6879 // First, handle some easy cases. We know the result cannot be equal at this
6880 // point so handle the ICI.isEquality() cases
6881 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006882 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006883 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006884 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006885
6886 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6887 // should have been folded away previously and not enter in here.
6888 Value *Result;
6889 if (isSignedCmp) {
6890 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006891 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006892 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006893 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006894 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006895 } else {
6896 // We're performing an unsigned comparison.
6897 if (isSignedExt) {
6898 // We're performing an unsigned comp with a sign extended value.
6899 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006900 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006901 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6902 NegOne, ICI.getName()), ICI);
6903 } else {
6904 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006905 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006906 }
6907 }
6908
6909 // Finally, return the value computed.
6910 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6911 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6912 return ReplaceInstUsesWith(ICI, Result);
6913 } else {
6914 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6915 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6916 "ICmp should be folded!");
6917 if (Constant *CI = dyn_cast<Constant>(Result))
6918 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6919 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006920 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006921 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006922}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006923
Reid Spencer832254e2007-02-02 02:16:23 +00006924Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6925 return commonShiftTransforms(I);
6926}
6927
6928Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6929 return commonShiftTransforms(I);
6930}
6931
6932Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006933 if (Instruction *R = commonShiftTransforms(I))
6934 return R;
6935
6936 Value *Op0 = I.getOperand(0);
6937
6938 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6939 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6940 if (CSI->isAllOnesValue())
6941 return ReplaceInstUsesWith(I, CSI);
6942
6943 // See if we can turn a signed shr into an unsigned shr.
6944 if (MaskedValueIsZero(Op0,
6945 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006946 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006947
6948 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006949}
6950
6951Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6952 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006953 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006954
6955 // shl X, 0 == X and shr X, 0 == X
6956 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006957 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006958 Op0 == Constant::getNullValue(Op0->getType()))
6959 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006960
Reid Spencere4d87aa2006-12-23 06:05:41 +00006961 if (isa<UndefValue>(Op0)) {
6962 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006963 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006964 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006965 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6966 }
6967 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006968 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6969 return ReplaceInstUsesWith(I, Op0);
6970 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006971 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006972 }
6973
Chris Lattner2eefe512004-04-09 19:05:30 +00006974 // Try to fold constant and into select arguments.
6975 if (isa<Constant>(Op0))
6976 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006977 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006978 return R;
6979
Reid Spencerb83eb642006-10-20 07:07:24 +00006980 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006981 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6982 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006983 return 0;
6984}
6985
Reid Spencerb83eb642006-10-20 07:07:24 +00006986Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006987 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006988 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006989
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006990 // See if we can simplify any instructions used by the instruction whose sole
6991 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006992 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6993 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6994 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006995 KnownZero, KnownOne))
6996 return &I;
6997
Chris Lattner4d5542c2006-01-06 07:12:35 +00006998 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6999 // of a signed value.
7000 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007001 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007002 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007003 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7004 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007005 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007006 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007007 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007008 }
7009
7010 // ((X*C1) << C2) == (X * (C1 << C2))
7011 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7012 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7013 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007014 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007015 ConstantExpr::getShl(BOOp, Op1));
7016
7017 // Try to fold constant and into select arguments.
7018 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7019 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7020 return R;
7021 if (isa<PHINode>(Op0))
7022 if (Instruction *NV = FoldOpIntoPhi(I))
7023 return NV;
7024
Chris Lattner8999dd32007-12-22 09:07:47 +00007025 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7026 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7027 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7028 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7029 // place. Don't try to do this transformation in this case. Also, we
7030 // require that the input operand is a shift-by-constant so that we have
7031 // confidence that the shifts will get folded together. We could do this
7032 // xform in more cases, but it is unlikely to be profitable.
7033 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7034 isa<ConstantInt>(TrOp->getOperand(1))) {
7035 // Okay, we'll do this xform. Make the shift of shift.
7036 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007037 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007038 I.getName());
7039 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7040
7041 // For logical shifts, the truncation has the effect of making the high
7042 // part of the register be zeros. Emulate this by inserting an AND to
7043 // clear the top bits as needed. This 'and' will usually be zapped by
7044 // other xforms later if dead.
7045 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7046 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7047 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7048
7049 // The mask we constructed says what the trunc would do if occurring
7050 // between the shifts. We want to know the effect *after* the second
7051 // shift. We know that it is a logical shift by a constant, so adjust the
7052 // mask as appropriate.
7053 if (I.getOpcode() == Instruction::Shl)
7054 MaskV <<= Op1->getZExtValue();
7055 else {
7056 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7057 MaskV = MaskV.lshr(Op1->getZExtValue());
7058 }
7059
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007060 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007061 TI->getName());
7062 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7063
7064 // Return the value truncated to the interesting size.
7065 return new TruncInst(And, I.getType());
7066 }
7067 }
7068
Chris Lattner4d5542c2006-01-06 07:12:35 +00007069 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007070 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7071 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7072 Value *V1, *V2;
7073 ConstantInt *CC;
7074 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007075 default: break;
7076 case Instruction::Add:
7077 case Instruction::And:
7078 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007079 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007080 // These operators commute.
7081 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007082 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7083 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007084 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007085 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007086 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007087 Op0BO->getName());
7088 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007089 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007090 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007091 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007092 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007093 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007094 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007095 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007096 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007097
Chris Lattner150f12a2005-09-18 06:30:59 +00007098 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007099 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007100 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007101 match(Op0BOOp1,
7102 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00007103 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7104 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007105 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007106 Op0BO->getOperand(0), Op1,
7107 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007108 InsertNewInstBefore(YS, I); // (Y << C)
7109 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007110 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007111 V1->getName()+".mask");
7112 InsertNewInstBefore(XM, I); // X & (CC << C)
7113
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007114 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007115 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007116 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007117
Reid Spencera07cb7d2007-02-02 14:41:37 +00007118 // FALL THROUGH.
7119 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007120 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007121 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7122 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007123 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007124 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007125 Op0BO->getOperand(1), Op1,
7126 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007127 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007128 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007129 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007130 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007131 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007132 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007133 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007134 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007135 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007136
Chris Lattner13d4ab42006-05-31 21:14:00 +00007137 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007138 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7139 match(Op0BO->getOperand(0),
7140 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007141 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007142 cast<BinaryOperator>(Op0BO->getOperand(0))
7143 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007144 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007145 Op0BO->getOperand(1), Op1,
7146 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007147 InsertNewInstBefore(YS, I); // (Y << C)
7148 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007149 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007150 V1->getName()+".mask");
7151 InsertNewInstBefore(XM, I); // X & (CC << C)
7152
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007153 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007154 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007155
Chris Lattner11021cb2005-09-18 05:12:10 +00007156 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007157 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007158 }
7159
7160
7161 // If the operand is an bitwise operator with a constant RHS, and the
7162 // shift is the only use, we can pull it out of the shift.
7163 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7164 bool isValid = true; // Valid only for And, Or, Xor
7165 bool highBitSet = false; // Transform if high bit of constant set?
7166
7167 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007168 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007169 case Instruction::Add:
7170 isValid = isLeftShift;
7171 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007172 case Instruction::Or:
7173 case Instruction::Xor:
7174 highBitSet = false;
7175 break;
7176 case Instruction::And:
7177 highBitSet = true;
7178 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007179 }
7180
7181 // If this is a signed shift right, and the high bit is modified
7182 // by the logical operation, do not perform the transformation.
7183 // The highBitSet boolean indicates the value of the high bit of
7184 // the constant which would cause it to be modified for this
7185 // operation.
7186 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007187 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007188 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007189
7190 if (isValid) {
7191 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7192
7193 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007194 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007195 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007196 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007197
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007198 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007199 NewRHS);
7200 }
7201 }
7202 }
7203 }
7204
Chris Lattnerad0124c2006-01-06 07:52:12 +00007205 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007206 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7207 if (ShiftOp && !ShiftOp->isShift())
7208 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007209
Reid Spencerb83eb642006-10-20 07:07:24 +00007210 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007211 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007212 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7213 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007214 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7215 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7216 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007217
Zhou Sheng4351c642007-04-02 08:20:41 +00007218 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007219 if (AmtSum > TypeBits)
7220 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007221
7222 const IntegerType *Ty = cast<IntegerType>(I.getType());
7223
7224 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007225 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007226 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007227 ConstantInt::get(Ty, AmtSum));
7228 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7229 I.getOpcode() == Instruction::AShr) {
7230 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007231 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007232 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7233 I.getOpcode() == Instruction::LShr) {
7234 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7235 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007236 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007237 InsertNewInstBefore(Shift, I);
7238
Zhou Shenge9e03f62007-03-28 15:02:20 +00007239 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007240 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007241 }
7242
Chris Lattnerb87056f2007-02-05 00:57:54 +00007243 // Okay, if we get here, one shift must be left, and the other shift must be
7244 // right. See if the amounts are equal.
7245 if (ShiftAmt1 == ShiftAmt2) {
7246 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7247 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007248 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007249 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007250 }
7251 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7252 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007253 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007254 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007255 }
7256 // We can simplify ((X << C) >>s C) into a trunc + sext.
7257 // NOTE: we could do this for any C, but that would make 'unusual' integer
7258 // types. For now, just stick to ones well-supported by the code
7259 // generators.
7260 const Type *SExtType = 0;
7261 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007262 case 1 :
7263 case 8 :
7264 case 16 :
7265 case 32 :
7266 case 64 :
7267 case 128:
7268 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7269 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007270 default: break;
7271 }
7272 if (SExtType) {
7273 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7274 InsertNewInstBefore(NewTrunc, I);
7275 return new SExtInst(NewTrunc, Ty);
7276 }
7277 // Otherwise, we can't handle it yet.
7278 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007279 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007280
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007281 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007282 if (I.getOpcode() == Instruction::Shl) {
7283 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7284 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007285 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007286 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007287 InsertNewInstBefore(Shift, I);
7288
Reid Spencer55702aa2007-03-25 21:11:44 +00007289 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007290 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007291 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007292
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007293 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007294 if (I.getOpcode() == Instruction::LShr) {
7295 assert(ShiftOp->getOpcode() == Instruction::Shl);
7296 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007297 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007298 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007299
Reid Spencerd5e30f02007-03-26 17:18:58 +00007300 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007301 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007302 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007303
7304 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7305 } else {
7306 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007307 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007308
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007309 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007310 if (I.getOpcode() == Instruction::Shl) {
7311 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7312 ShiftOp->getOpcode() == Instruction::AShr);
7313 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007314 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007315 ConstantInt::get(Ty, ShiftDiff));
7316 InsertNewInstBefore(Shift, I);
7317
Reid Spencer55702aa2007-03-25 21:11:44 +00007318 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007319 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007320 }
7321
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007322 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007323 if (I.getOpcode() == Instruction::LShr) {
7324 assert(ShiftOp->getOpcode() == Instruction::Shl);
7325 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007326 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007327 InsertNewInstBefore(Shift, I);
7328
Reid Spencer68d27cf2007-03-26 23:45:51 +00007329 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007330 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007331 }
7332
7333 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007334 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007335 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007336 return 0;
7337}
7338
Chris Lattnera1be5662002-05-02 17:06:02 +00007339
Chris Lattnercfd65102005-10-29 04:36:15 +00007340/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7341/// expression. If so, decompose it, returning some value X, such that Val is
7342/// X*Scale+Offset.
7343///
7344static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007345 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007346 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007347 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007348 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007349 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007350 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007351 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7352 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7353 if (I->getOpcode() == Instruction::Shl) {
7354 // This is a value scaled by '1 << the shift amt'.
7355 Scale = 1U << RHS->getZExtValue();
7356 Offset = 0;
7357 return I->getOperand(0);
7358 } else if (I->getOpcode() == Instruction::Mul) {
7359 // This value is scaled by 'RHS'.
7360 Scale = RHS->getZExtValue();
7361 Offset = 0;
7362 return I->getOperand(0);
7363 } else if (I->getOpcode() == Instruction::Add) {
7364 // We have X+C. Check to see if we really have (X*C2)+C1,
7365 // where C1 is divisible by C2.
7366 unsigned SubScale;
7367 Value *SubVal =
7368 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7369 Offset += RHS->getZExtValue();
7370 Scale = SubScale;
7371 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007372 }
7373 }
7374 }
7375
7376 // Otherwise, we can't look past this.
7377 Scale = 1;
7378 Offset = 0;
7379 return Val;
7380}
7381
7382
Chris Lattnerb3f83972005-10-24 06:03:58 +00007383/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7384/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007385Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007386 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007387 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007388
Chris Lattnerb53c2382005-10-24 06:22:12 +00007389 // Remove any uses of AI that are dead.
7390 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007391
Chris Lattnerb53c2382005-10-24 06:22:12 +00007392 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7393 Instruction *User = cast<Instruction>(*UI++);
7394 if (isInstructionTriviallyDead(User)) {
7395 while (UI != E && *UI == User)
7396 ++UI; // If this instruction uses AI more than once, don't break UI.
7397
Chris Lattnerb53c2382005-10-24 06:22:12 +00007398 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007399 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007400 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007401 }
7402 }
7403
Chris Lattnerb3f83972005-10-24 06:03:58 +00007404 // Get the type really allocated and the type casted to.
7405 const Type *AllocElTy = AI.getAllocatedType();
7406 const Type *CastElTy = PTy->getElementType();
7407 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007408
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007409 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7410 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007411 if (CastElTyAlign < AllocElTyAlign) return 0;
7412
Chris Lattner39387a52005-10-24 06:35:18 +00007413 // If the allocation has multiple uses, only promote it if we are strictly
7414 // increasing the alignment of the resultant allocation. If we keep it the
7415 // same, we open the door to infinite loops of various kinds.
7416 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7417
Duncan Sands514ab342007-11-01 20:53:16 +00007418 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7419 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007420 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007421
Chris Lattner455fcc82005-10-29 03:19:53 +00007422 // See if we can satisfy the modulus by pulling a scale out of the array
7423 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007424 unsigned ArraySizeScale;
7425 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007426 Value *NumElements = // See if the array size is a decomposable linear expr.
7427 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7428
Chris Lattner455fcc82005-10-29 03:19:53 +00007429 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7430 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007431 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7432 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007433
Chris Lattner455fcc82005-10-29 03:19:53 +00007434 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7435 Value *Amt = 0;
7436 if (Scale == 1) {
7437 Amt = NumElements;
7438 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007439 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007440 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7441 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007442 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007443 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007444 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007445 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007446 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007447 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007448 }
7449
Jeff Cohen86796be2007-04-04 16:58:57 +00007450 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7451 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007452 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007453 Amt = InsertNewInstBefore(Tmp, AI);
7454 }
7455
Chris Lattnerb3f83972005-10-24 06:03:58 +00007456 AllocationInst *New;
7457 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007458 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007459 else
Chris Lattner6934a042007-02-11 01:23:03 +00007460 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007461 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007462 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007463
7464 // If the allocation has multiple uses, insert a cast and change all things
7465 // that used it to use the new cast. This will also hack on CI, but it will
7466 // die soon.
7467 if (!AI.hasOneUse()) {
7468 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007469 // New is the allocation instruction, pointer typed. AI is the original
7470 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7471 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007472 InsertNewInstBefore(NewCast, AI);
7473 AI.replaceAllUsesWith(NewCast);
7474 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007475 return ReplaceInstUsesWith(CI, New);
7476}
7477
Chris Lattner70074e02006-05-13 02:06:03 +00007478/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007479/// and return it as type Ty without inserting any new casts and without
7480/// changing the computed value. This is used by code that tries to decide
7481/// whether promoting or shrinking integer operations to wider or smaller types
7482/// will allow us to eliminate a truncate or extend.
7483///
7484/// This is a truncation operation if Ty is smaller than V->getType(), or an
7485/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007486bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7487 unsigned CastOpc,
7488 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007489 // We can always evaluate constants in another type.
7490 if (isa<ConstantInt>(V))
7491 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007492
7493 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007494 if (!I) return false;
7495
7496 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007497
Chris Lattner951626b2007-08-02 06:11:14 +00007498 // If this is an extension or truncate, we can often eliminate it.
7499 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7500 // If this is a cast from the destination type, we can trivially eliminate
7501 // it, and this will remove a cast overall.
7502 if (I->getOperand(0)->getType() == Ty) {
7503 // If the first operand is itself a cast, and is eliminable, do not count
7504 // this as an eliminable cast. We would prefer to eliminate those two
7505 // casts first.
7506 if (!isa<CastInst>(I->getOperand(0)))
7507 ++NumCastsRemoved;
7508 return true;
7509 }
7510 }
7511
7512 // We can't extend or shrink something that has multiple uses: doing so would
7513 // require duplicating the instruction in general, which isn't profitable.
7514 if (!I->hasOneUse()) return false;
7515
Chris Lattner70074e02006-05-13 02:06:03 +00007516 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007517 case Instruction::Add:
7518 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007519 case Instruction::And:
7520 case Instruction::Or:
7521 case Instruction::Xor:
7522 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007523 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7524 NumCastsRemoved) &&
7525 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7526 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007527
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007528 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007529 // A multiply can be truncated by truncating its operands.
7530 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7531 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7532 NumCastsRemoved) &&
7533 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7534 NumCastsRemoved);
7535
Chris Lattner46b96052006-11-29 07:18:39 +00007536 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007537 // If we are truncating the result of this SHL, and if it's a shift of a
7538 // constant amount, we can always perform a SHL in a smaller type.
7539 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007540 uint32_t BitWidth = Ty->getBitWidth();
7541 if (BitWidth < OrigTy->getBitWidth() &&
7542 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007543 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7544 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007545 }
7546 break;
7547 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007548 // If this is a truncate of a logical shr, we can truncate it to a smaller
7549 // lshr iff we know that the bits we would otherwise be shifting in are
7550 // already zeros.
7551 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007552 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7553 uint32_t BitWidth = Ty->getBitWidth();
7554 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007555 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007556 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7557 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007558 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7559 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007560 }
7561 }
Chris Lattner46b96052006-11-29 07:18:39 +00007562 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007563 case Instruction::ZExt:
7564 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007565 case Instruction::Trunc:
7566 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007567 // can safely replace it. Note that replacing it does not reduce the number
7568 // of casts in the input.
7569 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007570 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007571
Reid Spencer3da59db2006-11-27 01:05:10 +00007572 break;
7573 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007574 // TODO: Can handle more cases here.
7575 break;
7576 }
7577
7578 return false;
7579}
7580
7581/// EvaluateInDifferentType - Given an expression that
7582/// CanEvaluateInDifferentType returns true for, actually insert the code to
7583/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007584Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007585 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007586 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007587 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007588
7589 // Otherwise, it must be an instruction.
7590 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007591 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007592 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007593 case Instruction::Add:
7594 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007595 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007596 case Instruction::And:
7597 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007598 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007599 case Instruction::AShr:
7600 case Instruction::LShr:
7601 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007602 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007603 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007604 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007605 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007606 break;
7607 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007608 case Instruction::Trunc:
7609 case Instruction::ZExt:
7610 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007611 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007612 // just return the source. There's no need to insert it because it is not
7613 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007614 if (I->getOperand(0)->getType() == Ty)
7615 return I->getOperand(0);
7616
Chris Lattner951626b2007-08-02 06:11:14 +00007617 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007618 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007619 Ty, I->getName());
7620 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007621 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007622 // TODO: Can handle more cases here.
7623 assert(0 && "Unreachable!");
7624 break;
7625 }
7626
7627 return InsertNewInstBefore(Res, *I);
7628}
7629
Reid Spencer3da59db2006-11-27 01:05:10 +00007630/// @brief Implement the transforms common to all CastInst visitors.
7631Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007632 Value *Src = CI.getOperand(0);
7633
Dan Gohman23d9d272007-05-11 21:10:54 +00007634 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007635 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007636 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007637 if (Instruction::CastOps opc =
7638 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7639 // The first cast (CSrc) is eliminable so we need to fix up or replace
7640 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007641 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007642 }
7643 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007644
Reid Spencer3da59db2006-11-27 01:05:10 +00007645 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007646 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7647 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7648 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007649
7650 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007651 if (isa<PHINode>(Src))
7652 if (Instruction *NV = FoldOpIntoPhi(CI))
7653 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007654
Reid Spencer3da59db2006-11-27 01:05:10 +00007655 return 0;
7656}
7657
Chris Lattnerd3e28342007-04-27 17:44:50 +00007658/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7659Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7660 Value *Src = CI.getOperand(0);
7661
Chris Lattnerd3e28342007-04-27 17:44:50 +00007662 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007663 // If casting the result of a getelementptr instruction with no offset, turn
7664 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007665 if (GEP->hasAllZeroIndices()) {
7666 // Changing the cast operand is usually not a good idea but it is safe
7667 // here because the pointer operand is being replaced with another
7668 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007669 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007670 CI.setOperand(0, GEP->getOperand(0));
7671 return &CI;
7672 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007673
7674 // If the GEP has a single use, and the base pointer is a bitcast, and the
7675 // GEP computes a constant offset, see if we can convert these three
7676 // instructions into fewer. This typically happens with unions and other
7677 // non-type-safe code.
7678 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7679 if (GEP->hasAllConstantIndices()) {
7680 // We are guaranteed to get a constant from EmitGEPOffset.
7681 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7682 int64_t Offset = OffsetV->getSExtValue();
7683
7684 // Get the base pointer input of the bitcast, and the type it points to.
7685 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7686 const Type *GEPIdxTy =
7687 cast<PointerType>(OrigBase->getType())->getElementType();
7688 if (GEPIdxTy->isSized()) {
7689 SmallVector<Value*, 8> NewIndices;
7690
Chris Lattnerc42e2262007-05-05 01:59:31 +00007691 // Start with the index over the outer type. Note that the type size
7692 // might be zero (even if the offset isn't zero) if the indexed type
7693 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007694 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007695 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007696 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007697 FirstIdx = Offset/TySize;
7698 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007699
Chris Lattnerc42e2262007-05-05 01:59:31 +00007700 // Handle silly modulus not returning values values [0..TySize).
7701 if (Offset < 0) {
7702 --FirstIdx;
7703 Offset += TySize;
7704 assert(Offset >= 0);
7705 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007706 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007707 }
7708
7709 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007710
7711 // Index into the types. If we fail, set OrigBase to null.
7712 while (Offset) {
7713 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7714 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007715 if (Offset < (int64_t)SL->getSizeInBytes()) {
7716 unsigned Elt = SL->getElementContainingOffset(Offset);
7717 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007718
Chris Lattner6b6aef82007-05-15 00:16:00 +00007719 Offset -= SL->getElementOffset(Elt);
7720 GEPIdxTy = STy->getElementType(Elt);
7721 } else {
7722 // Otherwise, we can't index into this, bail out.
7723 Offset = 0;
7724 OrigBase = 0;
7725 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007726 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7727 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007728 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007729 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7730 Offset %= EltSize;
7731 } else {
7732 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7733 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007734 GEPIdxTy = STy->getElementType();
7735 } else {
7736 // Otherwise, we can't index into this, bail out.
7737 Offset = 0;
7738 OrigBase = 0;
7739 }
7740 }
7741 if (OrigBase) {
7742 // If we were able to index down into an element, create the GEP
7743 // and bitcast the result. This eliminates one bitcast, potentially
7744 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007745 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7746 NewIndices.begin(),
7747 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007748 InsertNewInstBefore(NGEP, CI);
7749 NGEP->takeName(GEP);
7750
Chris Lattner9bc14642007-04-28 00:57:34 +00007751 if (isa<BitCastInst>(CI))
7752 return new BitCastInst(NGEP, CI.getType());
7753 assert(isa<PtrToIntInst>(CI));
7754 return new PtrToIntInst(NGEP, CI.getType());
7755 }
7756 }
7757 }
7758 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007759 }
7760
7761 return commonCastTransforms(CI);
7762}
7763
7764
7765
Chris Lattnerc739cd62007-03-03 05:27:34 +00007766/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7767/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007768/// cases.
7769/// @brief Implement the transforms common to CastInst with integer operands
7770Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7771 if (Instruction *Result = commonCastTransforms(CI))
7772 return Result;
7773
7774 Value *Src = CI.getOperand(0);
7775 const Type *SrcTy = Src->getType();
7776 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007777 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7778 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007779
Reid Spencer3da59db2006-11-27 01:05:10 +00007780 // See if we can simplify any instructions used by the LHS whose sole
7781 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007782 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7783 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007784 KnownZero, KnownOne))
7785 return &CI;
7786
7787 // If the source isn't an instruction or has more than one use then we
7788 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007789 Instruction *SrcI = dyn_cast<Instruction>(Src);
7790 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007791 return 0;
7792
Chris Lattnerc739cd62007-03-03 05:27:34 +00007793 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007794 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007795 if (!isa<BitCastInst>(CI) &&
7796 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007797 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007798 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007799 // eliminates the cast, so it is always a win. If this is a zero-extension,
7800 // we need to do an AND to maintain the clear top-part of the computation,
7801 // so we require that the input have eliminated at least one cast. If this
7802 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007803 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007804 bool DoXForm;
7805 switch (CI.getOpcode()) {
7806 default:
7807 // All the others use floating point so we shouldn't actually
7808 // get here because of the check above.
7809 assert(0 && "Unknown cast type");
7810 case Instruction::Trunc:
7811 DoXForm = true;
7812 break;
7813 case Instruction::ZExt:
7814 DoXForm = NumCastsRemoved >= 1;
7815 break;
7816 case Instruction::SExt:
7817 DoXForm = NumCastsRemoved >= 2;
7818 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007819 }
7820
7821 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007822 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7823 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007824 assert(Res->getType() == DestTy);
7825 switch (CI.getOpcode()) {
7826 default: assert(0 && "Unknown cast type!");
7827 case Instruction::Trunc:
7828 case Instruction::BitCast:
7829 // Just replace this cast with the result.
7830 return ReplaceInstUsesWith(CI, Res);
7831 case Instruction::ZExt: {
7832 // We need to emit an AND to clear the high bits.
7833 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007834 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7835 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007836 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007837 }
7838 case Instruction::SExt:
7839 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007840 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007841 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7842 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007843 }
7844 }
7845 }
7846
7847 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7848 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7849
7850 switch (SrcI->getOpcode()) {
7851 case Instruction::Add:
7852 case Instruction::Mul:
7853 case Instruction::And:
7854 case Instruction::Or:
7855 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007856 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007857 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7858 // Don't insert two casts if they cannot be eliminated. We allow
7859 // two casts to be inserted if the sizes are the same. This could
7860 // only be converting signedness, which is a noop.
7861 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007862 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7863 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007864 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007865 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7866 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007867 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007868 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007869 }
7870 }
7871
7872 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7873 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7874 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007875 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007876 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007877 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007878 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007879 }
7880 break;
7881 case Instruction::SDiv:
7882 case Instruction::UDiv:
7883 case Instruction::SRem:
7884 case Instruction::URem:
7885 // If we are just changing the sign, rewrite.
7886 if (DestBitSize == SrcBitSize) {
7887 // Don't insert two casts if they cannot be eliminated. We allow
7888 // two casts to be inserted if the sizes are the same. This could
7889 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007890 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7891 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007892 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7893 Op0, DestTy, SrcI);
7894 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7895 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007896 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007897 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7898 }
7899 }
7900 break;
7901
7902 case Instruction::Shl:
7903 // Allow changing the sign of the source operand. Do not allow
7904 // changing the size of the shift, UNLESS the shift amount is a
7905 // constant. We must not change variable sized shifts to a smaller
7906 // size, because it is undefined to shift more bits out than exist
7907 // in the value.
7908 if (DestBitSize == SrcBitSize ||
7909 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007910 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7911 Instruction::BitCast : Instruction::Trunc);
7912 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007913 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007914 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007915 }
7916 break;
7917 case Instruction::AShr:
7918 // If this is a signed shr, and if all bits shifted in are about to be
7919 // truncated off, turn it into an unsigned shr to allow greater
7920 // simplifications.
7921 if (DestBitSize < SrcBitSize &&
7922 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007923 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007924 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7925 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007926 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007927 }
7928 }
7929 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007930 }
7931 return 0;
7932}
7933
Chris Lattner8a9f5712007-04-11 06:57:46 +00007934Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007935 if (Instruction *Result = commonIntCastTransforms(CI))
7936 return Result;
7937
7938 Value *Src = CI.getOperand(0);
7939 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007940 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7941 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007942
7943 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7944 switch (SrcI->getOpcode()) {
7945 default: break;
7946 case Instruction::LShr:
7947 // We can shrink lshr to something smaller if we know the bits shifted in
7948 // are already zeros.
7949 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007950 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007951
7952 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007953 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007954 Value* SrcIOp0 = SrcI->getOperand(0);
7955 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007956 if (ShAmt >= DestBitWidth) // All zeros.
7957 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7958
7959 // Okay, we can shrink this. Truncate the input, then return a new
7960 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007961 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7962 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7963 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007964 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007965 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007966 } else { // This is a variable shr.
7967
7968 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7969 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7970 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007971 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007972 Value *One = ConstantInt::get(SrcI->getType(), 1);
7973
Reid Spencer832254e2007-02-02 02:16:23 +00007974 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007975 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007976 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007977 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007978 SrcI->getOperand(0),
7979 "tmp"), CI);
7980 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007981 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007982 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007983 }
7984 break;
7985 }
7986 }
7987
7988 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007989}
7990
Evan Chengb98a10e2008-03-24 00:21:34 +00007991/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7992/// in order to eliminate the icmp.
7993Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7994 bool DoXform) {
7995 // If we are just checking for a icmp eq of a single bit and zext'ing it
7996 // to an integer, then shift the bit to the appropriate place and then
7997 // cast to integer to avoid the comparison.
7998 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7999 const APInt &Op1CV = Op1C->getValue();
8000
8001 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8002 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8003 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8004 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8005 if (!DoXform) return ICI;
8006
8007 Value *In = ICI->getOperand(0);
8008 Value *Sh = ConstantInt::get(In->getType(),
8009 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008010 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008011 In->getName()+".lobit"),
8012 CI);
8013 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008014 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008015 false/*ZExt*/, "tmp", &CI);
8016
8017 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8018 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008019 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008020 In->getName()+".not"),
8021 CI);
8022 }
8023
8024 return ReplaceInstUsesWith(CI, In);
8025 }
8026
8027
8028
8029 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8030 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8031 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8032 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8033 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8034 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8035 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8036 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8037 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8038 // This only works for EQ and NE
8039 ICI->isEquality()) {
8040 // If Op1C some other power of two, convert:
8041 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8042 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8043 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8044 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8045
8046 APInt KnownZeroMask(~KnownZero);
8047 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8048 if (!DoXform) return ICI;
8049
8050 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8051 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8052 // (X&4) == 2 --> false
8053 // (X&4) != 2 --> true
8054 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8055 Res = ConstantExpr::getZExt(Res, CI.getType());
8056 return ReplaceInstUsesWith(CI, Res);
8057 }
8058
8059 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8060 Value *In = ICI->getOperand(0);
8061 if (ShiftAmt) {
8062 // Perform a logical shr by shiftamt.
8063 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008064 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008065 ConstantInt::get(In->getType(), ShiftAmt),
8066 In->getName()+".lobit"), CI);
8067 }
8068
8069 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8070 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008071 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008072 InsertNewInstBefore(cast<Instruction>(In), CI);
8073 }
8074
8075 if (CI.getType() == In->getType())
8076 return ReplaceInstUsesWith(CI, In);
8077 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008078 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008079 }
8080 }
8081 }
8082
8083 return 0;
8084}
8085
Chris Lattner8a9f5712007-04-11 06:57:46 +00008086Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008087 // If one of the common conversion will work ..
8088 if (Instruction *Result = commonIntCastTransforms(CI))
8089 return Result;
8090
8091 Value *Src = CI.getOperand(0);
8092
8093 // If this is a cast of a cast
8094 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008095 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8096 // types and if the sizes are just right we can convert this into a logical
8097 // 'and' which will be much cheaper than the pair of casts.
8098 if (isa<TruncInst>(CSrc)) {
8099 // Get the sizes of the types involved
8100 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008101 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8102 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8103 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008104 // If we're actually extending zero bits and the trunc is a no-op
8105 if (MidSize < DstSize && SrcSize == DstSize) {
8106 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00008107 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00008108 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00008109 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008110 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00008111 // Unfortunately, if the type changed, we need to cast it back.
8112 if (And->getType() != CI.getType()) {
8113 And->setName(CSrc->getName()+".mask");
8114 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008115 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00008116 }
8117 return And;
8118 }
8119 }
8120 }
8121
Evan Chengb98a10e2008-03-24 00:21:34 +00008122 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8123 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008124
Evan Chengb98a10e2008-03-24 00:21:34 +00008125 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8126 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8127 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8128 // of the (zext icmp) will be transformed.
8129 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8130 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8131 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8132 (transformZExtICmp(LHS, CI, false) ||
8133 transformZExtICmp(RHS, CI, false))) {
8134 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8135 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008136 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008137 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008138 }
8139
Reid Spencer3da59db2006-11-27 01:05:10 +00008140 return 0;
8141}
8142
Chris Lattner8a9f5712007-04-11 06:57:46 +00008143Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008144 if (Instruction *I = commonIntCastTransforms(CI))
8145 return I;
8146
Chris Lattner8a9f5712007-04-11 06:57:46 +00008147 Value *Src = CI.getOperand(0);
8148
8149 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
8150 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
8151 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8152 // If we are just checking for a icmp eq of a single bit and zext'ing it
8153 // to an integer, then shift the bit to the appropriate place and then
8154 // cast to integer to avoid the comparison.
8155 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8156 const APInt &Op1CV = Op1C->getValue();
8157
8158 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8159 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8160 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8161 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8162 Value *In = ICI->getOperand(0);
8163 Value *Sh = ConstantInt::get(In->getType(),
8164 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008165 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00008166 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008167 CI);
8168 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008169 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008170 true/*SExt*/, "tmp", &CI);
8171
8172 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008173 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00008174 In->getName()+".not"), CI);
8175
8176 return ReplaceInstUsesWith(CI, In);
8177 }
8178 }
8179 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00008180
8181 // See if the value being truncated is already sign extended. If so, just
8182 // eliminate the trunc/sext pair.
8183 if (getOpcode(Src) == Instruction::Trunc) {
8184 Value *Op = cast<User>(Src)->getOperand(0);
8185 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8186 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8187 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8188 unsigned NumSignBits = ComputeNumSignBits(Op);
8189
8190 if (OpBits == DestBits) {
8191 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8192 // bits, it is already ready.
8193 if (NumSignBits > DestBits-MidBits)
8194 return ReplaceInstUsesWith(CI, Op);
8195 } else if (OpBits < DestBits) {
8196 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8197 // bits, just sext from i32.
8198 if (NumSignBits > OpBits-MidBits)
8199 return new SExtInst(Op, CI.getType(), "tmp");
8200 } else {
8201 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8202 // bits, just truncate to i32.
8203 if (NumSignBits > OpBits-MidBits)
8204 return new TruncInst(Op, CI.getType(), "tmp");
8205 }
8206 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00008207
Chris Lattnerba417832007-04-11 06:12:58 +00008208 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008209}
8210
Chris Lattnerb7530652008-01-27 05:29:54 +00008211/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8212/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008213static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008214 APFloat F = CFP->getValueAPF();
8215 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00008216 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008217 return 0;
8218}
8219
8220/// LookThroughFPExtensions - If this is an fp extension instruction, look
8221/// through it until we get the source value.
8222static Value *LookThroughFPExtensions(Value *V) {
8223 if (Instruction *I = dyn_cast<Instruction>(V))
8224 if (I->getOpcode() == Instruction::FPExt)
8225 return LookThroughFPExtensions(I->getOperand(0));
8226
8227 // If this value is a constant, return the constant in the smallest FP type
8228 // that can accurately represent it. This allows us to turn
8229 // (float)((double)X+2.0) into x+2.0f.
8230 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8231 if (CFP->getType() == Type::PPC_FP128Ty)
8232 return V; // No constant folding of this.
8233 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008234 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008235 return V;
8236 if (CFP->getType() == Type::DoubleTy)
8237 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008238 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008239 return V;
8240 // Don't try to shrink to various long double types.
8241 }
8242
8243 return V;
8244}
8245
8246Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8247 if (Instruction *I = commonCastTransforms(CI))
8248 return I;
8249
8250 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8251 // smaller than the destination type, we can eliminate the truncate by doing
8252 // the add as the smaller type. This applies to add/sub/mul/div as well as
8253 // many builtins (sqrt, etc).
8254 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8255 if (OpI && OpI->hasOneUse()) {
8256 switch (OpI->getOpcode()) {
8257 default: break;
8258 case Instruction::Add:
8259 case Instruction::Sub:
8260 case Instruction::Mul:
8261 case Instruction::FDiv:
8262 case Instruction::FRem:
8263 const Type *SrcTy = OpI->getType();
8264 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8265 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8266 if (LHSTrunc->getType() != SrcTy &&
8267 RHSTrunc->getType() != SrcTy) {
8268 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8269 // If the source types were both smaller than the destination type of
8270 // the cast, do this xform.
8271 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8272 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8273 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8274 CI.getType(), CI);
8275 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8276 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008277 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008278 }
8279 }
8280 break;
8281 }
8282 }
8283 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008284}
8285
8286Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8287 return commonCastTransforms(CI);
8288}
8289
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008290Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8291 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8292 // mantissa to accurately represent all values of X. For example, do not
8293 // do this with i64->float->i64.
8294 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8295 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8296 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00008297 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008298 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8299
8300 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008301}
8302
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008303Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8304 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8305 // mantissa to accurately represent all values of X. For example, do not
8306 // do this with i64->float->i64.
8307 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8308 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8309 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00008310 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008311 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8312
8313 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008314}
8315
8316Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8317 return commonCastTransforms(CI);
8318}
8319
8320Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8321 return commonCastTransforms(CI);
8322}
8323
8324Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008325 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008326}
8327
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008328Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8329 if (Instruction *I = commonCastTransforms(CI))
8330 return I;
8331
8332 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8333 if (!DestPointee->isSized()) return 0;
8334
8335 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8336 ConstantInt *Cst;
8337 Value *X;
8338 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8339 m_ConstantInt(Cst)))) {
8340 // If the source and destination operands have the same type, see if this
8341 // is a single-index GEP.
8342 if (X->getType() == CI.getType()) {
8343 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00008344 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008345
8346 // Convert the constant to intptr type.
8347 APInt Offset = Cst->getValue();
8348 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8349
8350 // If Offset is evenly divisible by Size, we can do this xform.
8351 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8352 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008353 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008354 }
8355 }
8356 // TODO: Could handle other cases, e.g. where add is indexing into field of
8357 // struct etc.
8358 } else if (CI.getOperand(0)->hasOneUse() &&
8359 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8360 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8361 // "inttoptr+GEP" instead of "add+intptr".
8362
8363 // Get the size of the pointee type.
8364 uint64_t Size = TD->getABITypeSize(DestPointee);
8365
8366 // Convert the constant to intptr type.
8367 APInt Offset = Cst->getValue();
8368 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8369
8370 // If Offset is evenly divisible by Size, we can do this xform.
8371 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8372 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8373
8374 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8375 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008376 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008377 }
8378 }
8379 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008380}
8381
Chris Lattnerd3e28342007-04-27 17:44:50 +00008382Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008383 // If the operands are integer typed then apply the integer transforms,
8384 // otherwise just apply the common ones.
8385 Value *Src = CI.getOperand(0);
8386 const Type *SrcTy = Src->getType();
8387 const Type *DestTy = CI.getType();
8388
Chris Lattner42a75512007-01-15 02:27:26 +00008389 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008390 if (Instruction *Result = commonIntCastTransforms(CI))
8391 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008392 } else if (isa<PointerType>(SrcTy)) {
8393 if (Instruction *I = commonPointerCastTransforms(CI))
8394 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008395 } else {
8396 if (Instruction *Result = commonCastTransforms(CI))
8397 return Result;
8398 }
8399
8400
8401 // Get rid of casts from one type to the same type. These are useless and can
8402 // be replaced by the operand.
8403 if (DestTy == Src->getType())
8404 return ReplaceInstUsesWith(CI, Src);
8405
Reid Spencer3da59db2006-11-27 01:05:10 +00008406 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008407 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8408 const Type *DstElTy = DstPTy->getElementType();
8409 const Type *SrcElTy = SrcPTy->getElementType();
8410
Nate Begeman83ad90a2008-03-31 00:22:16 +00008411 // If the address spaces don't match, don't eliminate the bitcast, which is
8412 // required for changing types.
8413 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8414 return 0;
8415
Chris Lattnerd3e28342007-04-27 17:44:50 +00008416 // If we are casting a malloc or alloca to a pointer to a type of the same
8417 // size, rewrite the allocation instruction to allocate the "right" type.
8418 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8419 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8420 return V;
8421
Chris Lattnerd717c182007-05-05 22:32:24 +00008422 // If the source and destination are pointers, and this cast is equivalent
8423 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008424 // This can enhance SROA and other transforms that want type-safe pointers.
8425 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8426 unsigned NumZeros = 0;
8427 while (SrcElTy != DstElTy &&
8428 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8429 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8430 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8431 ++NumZeros;
8432 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008433
Chris Lattnerd3e28342007-04-27 17:44:50 +00008434 // If we found a path from the src to dest, create the getelementptr now.
8435 if (SrcElTy == DstElTy) {
8436 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008437 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8438 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008439 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008440 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008441
Reid Spencer3da59db2006-11-27 01:05:10 +00008442 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8443 if (SVI->hasOneUse()) {
8444 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8445 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008446 if (isa<VectorType>(DestTy) &&
8447 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008448 SVI->getType()->getNumElements()) {
8449 CastInst *Tmp;
8450 // If either of the operands is a cast from CI.getType(), then
8451 // evaluating the shuffle in the casted destination's type will allow
8452 // us to eliminate at least one cast.
8453 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8454 Tmp->getOperand(0)->getType() == DestTy) ||
8455 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8456 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008457 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8458 SVI->getOperand(0), DestTy, &CI);
8459 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8460 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008461 // Return a new shuffle vector. Use the same element ID's, as we
8462 // know the vector types match #elts.
8463 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008464 }
8465 }
8466 }
8467 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008468 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008469}
8470
Chris Lattnere576b912004-04-09 23:46:01 +00008471/// GetSelectFoldableOperands - We want to turn code that looks like this:
8472/// %C = or %A, %B
8473/// %D = select %cond, %C, %A
8474/// into:
8475/// %C = select %cond, %B, 0
8476/// %D = or %A, %C
8477///
8478/// Assuming that the specified instruction is an operand to the select, return
8479/// a bitmask indicating which operands of this instruction are foldable if they
8480/// equal the other incoming value of the select.
8481///
8482static unsigned GetSelectFoldableOperands(Instruction *I) {
8483 switch (I->getOpcode()) {
8484 case Instruction::Add:
8485 case Instruction::Mul:
8486 case Instruction::And:
8487 case Instruction::Or:
8488 case Instruction::Xor:
8489 return 3; // Can fold through either operand.
8490 case Instruction::Sub: // Can only fold on the amount subtracted.
8491 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008492 case Instruction::LShr:
8493 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008494 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008495 default:
8496 return 0; // Cannot fold
8497 }
8498}
8499
8500/// GetSelectFoldableConstant - For the same transformation as the previous
8501/// function, return the identity constant that goes into the select.
8502static Constant *GetSelectFoldableConstant(Instruction *I) {
8503 switch (I->getOpcode()) {
8504 default: assert(0 && "This cannot happen!"); abort();
8505 case Instruction::Add:
8506 case Instruction::Sub:
8507 case Instruction::Or:
8508 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008509 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008510 case Instruction::LShr:
8511 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008512 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008513 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008514 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008515 case Instruction::Mul:
8516 return ConstantInt::get(I->getType(), 1);
8517 }
8518}
8519
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008520/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8521/// have the same opcode and only one use each. Try to simplify this.
8522Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8523 Instruction *FI) {
8524 if (TI->getNumOperands() == 1) {
8525 // If this is a non-volatile load or a cast from the same type,
8526 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008527 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008528 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8529 return 0;
8530 } else {
8531 return 0; // unknown unary op.
8532 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008533
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008534 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008535 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8536 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008537 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008538 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008539 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008540 }
8541
Reid Spencer832254e2007-02-02 02:16:23 +00008542 // Only handle binary operators here.
8543 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008544 return 0;
8545
8546 // Figure out if the operations have any operands in common.
8547 Value *MatchOp, *OtherOpT, *OtherOpF;
8548 bool MatchIsOpZero;
8549 if (TI->getOperand(0) == FI->getOperand(0)) {
8550 MatchOp = TI->getOperand(0);
8551 OtherOpT = TI->getOperand(1);
8552 OtherOpF = FI->getOperand(1);
8553 MatchIsOpZero = true;
8554 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8555 MatchOp = TI->getOperand(1);
8556 OtherOpT = TI->getOperand(0);
8557 OtherOpF = FI->getOperand(0);
8558 MatchIsOpZero = false;
8559 } else if (!TI->isCommutative()) {
8560 return 0;
8561 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8562 MatchOp = TI->getOperand(0);
8563 OtherOpT = TI->getOperand(1);
8564 OtherOpF = FI->getOperand(0);
8565 MatchIsOpZero = true;
8566 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8567 MatchOp = TI->getOperand(1);
8568 OtherOpT = TI->getOperand(0);
8569 OtherOpF = FI->getOperand(1);
8570 MatchIsOpZero = true;
8571 } else {
8572 return 0;
8573 }
8574
8575 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008576 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8577 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008578 InsertNewInstBefore(NewSI, SI);
8579
8580 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8581 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008582 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008583 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008584 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008585 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008586 assert(0 && "Shouldn't get here");
8587 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008588}
8589
Chris Lattner3d69f462004-03-12 05:52:32 +00008590Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008591 Value *CondVal = SI.getCondition();
8592 Value *TrueVal = SI.getTrueValue();
8593 Value *FalseVal = SI.getFalseValue();
8594
8595 // select true, X, Y -> X
8596 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008597 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008598 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008599
8600 // select C, X, X -> X
8601 if (TrueVal == FalseVal)
8602 return ReplaceInstUsesWith(SI, TrueVal);
8603
Chris Lattnere87597f2004-10-16 18:11:37 +00008604 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8605 return ReplaceInstUsesWith(SI, FalseVal);
8606 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8607 return ReplaceInstUsesWith(SI, TrueVal);
8608 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8609 if (isa<Constant>(TrueVal))
8610 return ReplaceInstUsesWith(SI, TrueVal);
8611 else
8612 return ReplaceInstUsesWith(SI, FalseVal);
8613 }
8614
Reid Spencer4fe16d62007-01-11 18:21:29 +00008615 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008616 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008617 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008618 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008619 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008620 } else {
8621 // Change: A = select B, false, C --> A = and !B, C
8622 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008623 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008624 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008625 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008626 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008627 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008628 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008629 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008630 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008631 } else {
8632 // Change: A = select B, C, true --> A = or !B, C
8633 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008634 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008635 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008636 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008637 }
8638 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008639
8640 // select a, b, a -> a&b
8641 // select a, a, b -> a|b
8642 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008643 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008644 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008645 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008646 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008647
Chris Lattner2eefe512004-04-09 19:05:30 +00008648 // Selecting between two integer constants?
8649 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8650 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008651 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008652 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008653 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008654 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008655 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008656 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008657 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008658 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008659 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008660 }
Chris Lattnerba417832007-04-11 06:12:58 +00008661
8662 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008663
Reid Spencere4d87aa2006-12-23 06:05:41 +00008664 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008665
Reid Spencere4d87aa2006-12-23 06:05:41 +00008666 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008667 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008668 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008669 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008670 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008671 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008672 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008673 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008674 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008675 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008676 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008677 InsertNewInstBefore(SRA, SI);
8678
Reid Spencer3da59db2006-11-27 01:05:10 +00008679 // Finally, convert to the type of the select RHS. We figure out
8680 // if this requires a SExt, Trunc or BitCast based on the sizes.
8681 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008682 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8683 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008684 if (SRASize < SISize)
8685 opc = Instruction::SExt;
8686 else if (SRASize > SISize)
8687 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008688 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008689 }
8690 }
8691
8692
8693 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008694 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008695 // non-constant value, eliminate this whole mess. This corresponds to
8696 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008697 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008698 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008699 cast<Constant>(IC->getOperand(1))->isNullValue())
8700 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8701 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008702 isa<ConstantInt>(ICA->getOperand(1)) &&
8703 (ICA->getOperand(1) == TrueValC ||
8704 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008705 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8706 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008707 // know whether we have a icmp_ne or icmp_eq and whether the
8708 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008709 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008710 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008711 Value *V = ICA;
8712 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008713 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008714 Instruction::Xor, V, ICA->getOperand(1)), SI);
8715 return ReplaceInstUsesWith(SI, V);
8716 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008717 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008718 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008719
8720 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008721 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8722 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008723 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008724 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8725 // This is not safe in general for floating point:
8726 // consider X== -0, Y== +0.
8727 // It becomes safe if either operand is a nonzero constant.
8728 ConstantFP *CFPt, *CFPf;
8729 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8730 !CFPt->getValueAPF().isZero()) ||
8731 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8732 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008733 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008734 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008735 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008736 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008737 return ReplaceInstUsesWith(SI, TrueVal);
8738 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8739
Reid Spencere4d87aa2006-12-23 06:05:41 +00008740 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008741 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008742 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8743 // This is not safe in general for floating point:
8744 // consider X== -0, Y== +0.
8745 // It becomes safe if either operand is a nonzero constant.
8746 ConstantFP *CFPt, *CFPf;
8747 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8748 !CFPt->getValueAPF().isZero()) ||
8749 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8750 !CFPf->getValueAPF().isZero()))
8751 return ReplaceInstUsesWith(SI, FalseVal);
8752 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008753 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008754 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8755 return ReplaceInstUsesWith(SI, TrueVal);
8756 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8757 }
8758 }
8759
8760 // See if we are selecting two values based on a comparison of the two values.
8761 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8762 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8763 // Transform (X == Y) ? X : Y -> Y
8764 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8765 return ReplaceInstUsesWith(SI, FalseVal);
8766 // Transform (X != Y) ? X : Y -> X
8767 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8768 return ReplaceInstUsesWith(SI, TrueVal);
8769 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8770
8771 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8772 // Transform (X == Y) ? Y : X -> X
8773 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8774 return ReplaceInstUsesWith(SI, FalseVal);
8775 // Transform (X != Y) ? Y : X -> Y
8776 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008777 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008778 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8779 }
8780 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008781
Chris Lattner87875da2005-01-13 22:52:24 +00008782 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8783 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8784 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008785 Instruction *AddOp = 0, *SubOp = 0;
8786
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008787 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8788 if (TI->getOpcode() == FI->getOpcode())
8789 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8790 return IV;
8791
8792 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8793 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008794 if (TI->getOpcode() == Instruction::Sub &&
8795 FI->getOpcode() == Instruction::Add) {
8796 AddOp = FI; SubOp = TI;
8797 } else if (FI->getOpcode() == Instruction::Sub &&
8798 TI->getOpcode() == Instruction::Add) {
8799 AddOp = TI; SubOp = FI;
8800 }
8801
8802 if (AddOp) {
8803 Value *OtherAddOp = 0;
8804 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8805 OtherAddOp = AddOp->getOperand(1);
8806 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8807 OtherAddOp = AddOp->getOperand(0);
8808 }
8809
8810 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008811 // So at this point we know we have (Y -> OtherAddOp):
8812 // select C, (add X, Y), (sub X, Z)
8813 Value *NegVal; // Compute -Z
8814 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8815 NegVal = ConstantExpr::getNeg(C);
8816 } else {
8817 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008818 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008819 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008820
8821 Value *NewTrueOp = OtherAddOp;
8822 Value *NewFalseOp = NegVal;
8823 if (AddOp != TI)
8824 std::swap(NewTrueOp, NewFalseOp);
8825 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008826 SelectInst::Create(CondVal, NewTrueOp,
8827 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008828
8829 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008830 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008831 }
8832 }
8833 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008834
Chris Lattnere576b912004-04-09 23:46:01 +00008835 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008836 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008837 // See the comment above GetSelectFoldableOperands for a description of the
8838 // transformation we are doing here.
8839 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8840 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8841 !isa<Constant>(FalseVal))
8842 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8843 unsigned OpToFold = 0;
8844 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8845 OpToFold = 1;
8846 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8847 OpToFold = 2;
8848 }
8849
8850 if (OpToFold) {
8851 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008852 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008853 SelectInst::Create(SI.getCondition(),
8854 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008855 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008856 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008857 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008858 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008859 else {
8860 assert(0 && "Unknown instruction!!");
8861 }
8862 }
8863 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008864
Chris Lattnere576b912004-04-09 23:46:01 +00008865 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8866 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8867 !isa<Constant>(TrueVal))
8868 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8869 unsigned OpToFold = 0;
8870 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8871 OpToFold = 1;
8872 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8873 OpToFold = 2;
8874 }
8875
8876 if (OpToFold) {
8877 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008878 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008879 SelectInst::Create(SI.getCondition(), C,
8880 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008881 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008882 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008883 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008884 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008885 else
Chris Lattnere576b912004-04-09 23:46:01 +00008886 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008887 }
8888 }
8889 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008890
8891 if (BinaryOperator::isNot(CondVal)) {
8892 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8893 SI.setOperand(1, FalseVal);
8894 SI.setOperand(2, TrueVal);
8895 return &SI;
8896 }
8897
Chris Lattner3d69f462004-03-12 05:52:32 +00008898 return 0;
8899}
8900
Dan Gohmaneee962e2008-04-10 18:43:06 +00008901/// EnforceKnownAlignment - If the specified pointer points to an object that
8902/// we control, modify the object's alignment to PrefAlign. This isn't
8903/// often possible though. If alignment is important, a more reliable approach
8904/// is to simply align all global variables and allocation instructions to
8905/// their preferred alignment from the beginning.
8906///
8907static unsigned EnforceKnownAlignment(Value *V,
8908 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008909
Dan Gohmaneee962e2008-04-10 18:43:06 +00008910 User *U = dyn_cast<User>(V);
8911 if (!U) return Align;
8912
8913 switch (getOpcode(U)) {
8914 default: break;
8915 case Instruction::BitCast:
8916 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8917 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008918 // If all indexes are zero, it is just the alignment of the base pointer.
8919 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008920 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8921 if (!isa<Constant>(U->getOperand(i)) ||
8922 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008923 AllZeroOperands = false;
8924 break;
8925 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008926
8927 if (AllZeroOperands) {
8928 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008929 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008930 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008931 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008932 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008933 }
8934
8935 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8936 // If there is a large requested alignment and we can, bump up the alignment
8937 // of the global.
8938 if (!GV->isDeclaration()) {
8939 GV->setAlignment(PrefAlign);
8940 Align = PrefAlign;
8941 }
8942 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8943 // If there is a requested alignment and if this is an alloca, round up. We
8944 // don't do this for malloc, because some systems can't respect the request.
8945 if (isa<AllocaInst>(AI)) {
8946 AI->setAlignment(PrefAlign);
8947 Align = PrefAlign;
8948 }
8949 }
8950
8951 return Align;
8952}
8953
8954/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8955/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8956/// and it is more than the alignment of the ultimate object, see if we can
8957/// increase the alignment of the ultimate object, making this check succeed.
8958unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8959 unsigned PrefAlign) {
8960 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8961 sizeof(PrefAlign) * CHAR_BIT;
8962 APInt Mask = APInt::getAllOnesValue(BitWidth);
8963 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8964 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8965 unsigned TrailZ = KnownZero.countTrailingOnes();
8966 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8967
8968 if (PrefAlign > Align)
8969 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8970
8971 // We don't need to make any adjustment.
8972 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008973}
8974
Chris Lattnerf497b022008-01-13 23:50:23 +00008975Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008976 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8977 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008978 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8979 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8980
8981 if (CopyAlign < MinAlign) {
8982 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8983 return MI;
8984 }
8985
8986 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8987 // load/store.
8988 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8989 if (MemOpLength == 0) return 0;
8990
Chris Lattner37ac6082008-01-14 00:28:35 +00008991 // Source and destination pointer types are always "i8*" for intrinsic. See
8992 // if the size is something we can handle with a single primitive load/store.
8993 // A single load+store correctly handles overlapping memory in the memmove
8994 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008995 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008996 if (Size == 0) return MI; // Delete this mem transfer.
8997
8998 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008999 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009000
Chris Lattner37ac6082008-01-14 00:28:35 +00009001 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009002 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009003
9004 // Memcpy forces the use of i8* for the source and destination. That means
9005 // that if you're using memcpy to move one double around, you'll get a cast
9006 // from double* to i8*. We'd much rather use a double load+store rather than
9007 // an i64 load+store, here because this improves the odds that the source or
9008 // dest address will be promotable. See if we can find a better type than the
9009 // integer datatype.
9010 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9011 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9012 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9013 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9014 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009015 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009016 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9017 if (STy->getNumElements() == 1)
9018 SrcETy = STy->getElementType(0);
9019 else
9020 break;
9021 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9022 if (ATy->getNumElements() == 1)
9023 SrcETy = ATy->getElementType();
9024 else
9025 break;
9026 } else
9027 break;
9028 }
9029
Dan Gohman8f8e2692008-05-23 01:52:21 +00009030 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009031 NewPtrTy = PointerType::getUnqual(SrcETy);
9032 }
9033 }
9034
9035
Chris Lattnerf497b022008-01-13 23:50:23 +00009036 // If the memcpy/memmove provides better alignment info than we can
9037 // infer, use it.
9038 SrcAlign = std::max(SrcAlign, CopyAlign);
9039 DstAlign = std::max(DstAlign, CopyAlign);
9040
9041 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9042 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009043 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9044 InsertNewInstBefore(L, *MI);
9045 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9046
9047 // Set the size of the copy to 0, it will be deleted on the next iteration.
9048 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9049 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009050}
Chris Lattner3d69f462004-03-12 05:52:32 +00009051
Chris Lattner69ea9d22008-04-30 06:39:11 +00009052Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9053 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9054 if (MI->getAlignment()->getZExtValue() < Alignment) {
9055 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9056 return MI;
9057 }
9058
9059 // Extract the length and alignment and fill if they are constant.
9060 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9061 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9062 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9063 return 0;
9064 uint64_t Len = LenC->getZExtValue();
9065 Alignment = MI->getAlignment()->getZExtValue();
9066
9067 // If the length is zero, this is a no-op
9068 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9069
9070 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9071 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9072 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9073
9074 Value *Dest = MI->getDest();
9075 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9076
9077 // Alignment 0 is identity for alignment 1 for memset, but not store.
9078 if (Alignment == 0) Alignment = 1;
9079
9080 // Extract the fill value and store.
9081 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9082 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9083 Alignment), *MI);
9084
9085 // Set the size of the copy to 0, it will be deleted on the next iteration.
9086 MI->setLength(Constant::getNullValue(LenC->getType()));
9087 return MI;
9088 }
9089
9090 return 0;
9091}
9092
9093
Chris Lattner8b0ea312006-01-13 20:11:04 +00009094/// visitCallInst - CallInst simplification. This mostly only handles folding
9095/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9096/// the heavy lifting.
9097///
Chris Lattner9fe38862003-06-19 17:00:31 +00009098Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009099 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9100 if (!II) return visitCallSite(&CI);
9101
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009102 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9103 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009104 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009105 bool Changed = false;
9106
9107 // memmove/cpy/set of zero bytes is a noop.
9108 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9109 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9110
Chris Lattner35b9e482004-10-12 04:52:52 +00009111 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009112 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009113 // Replace the instruction with just byte operations. We would
9114 // transform other cases to loads/stores, but we don't know if
9115 // alignment is sufficient.
9116 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009117 }
9118
Chris Lattner35b9e482004-10-12 04:52:52 +00009119 // If we have a memmove and the source operation is a constant global,
9120 // then the source and dest pointers can't alias, so we can change this
9121 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009122 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009123 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9124 if (GVSrc->isConstant()) {
9125 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00009126 Intrinsic::ID MemCpyID;
9127 if (CI.getOperand(3)->getType() == Type::Int32Ty)
9128 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00009129 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00009130 MemCpyID = Intrinsic::memcpy_i64;
9131 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00009132 Changed = true;
9133 }
Chris Lattnera935db82008-05-28 05:30:41 +00009134
9135 // memmove(x,x,size) -> noop.
9136 if (MMI->getSource() == MMI->getDest())
9137 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009138 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009139
Chris Lattner95a959d2006-03-06 20:18:44 +00009140 // If we can determine a pointer alignment that is bigger than currently
9141 // set, update the alignment.
9142 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009143 if (Instruction *I = SimplifyMemTransfer(MI))
9144 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009145 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9146 if (Instruction *I = SimplifyMemSet(MSI))
9147 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009148 }
9149
Chris Lattner8b0ea312006-01-13 20:11:04 +00009150 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009151 } else {
9152 switch (II->getIntrinsicID()) {
9153 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00009154 case Intrinsic::ppc_altivec_lvx:
9155 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009156 case Intrinsic::x86_sse_loadu_ps:
9157 case Intrinsic::x86_sse2_loadu_pd:
9158 case Intrinsic::x86_sse2_loadu_dq:
9159 // Turn PPC lvx -> load if the pointer is known aligned.
9160 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009161 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00009162 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9163 PointerType::getUnqual(II->getType()),
9164 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009165 return new LoadInst(Ptr);
9166 }
9167 break;
9168 case Intrinsic::ppc_altivec_stvx:
9169 case Intrinsic::ppc_altivec_stvxl:
9170 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009171 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009172 const Type *OpPtrTy =
9173 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009174 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009175 return new StoreInst(II->getOperand(1), Ptr);
9176 }
9177 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009178 case Intrinsic::x86_sse_storeu_ps:
9179 case Intrinsic::x86_sse2_storeu_pd:
9180 case Intrinsic::x86_sse2_storeu_dq:
9181 case Intrinsic::x86_sse2_storel_dq:
9182 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009183 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009184 const Type *OpPtrTy =
9185 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009186 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009187 return new StoreInst(II->getOperand(2), Ptr);
9188 }
9189 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00009190
9191 case Intrinsic::x86_sse_cvttss2si: {
9192 // These intrinsics only demands the 0th element of its input vector. If
9193 // we can simplify the input based on that, do so now.
9194 uint64_t UndefElts;
9195 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9196 UndefElts)) {
9197 II->setOperand(1, V);
9198 return II;
9199 }
9200 break;
9201 }
9202
Chris Lattnere2ed0572006-04-06 19:19:17 +00009203 case Intrinsic::ppc_altivec_vperm:
9204 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009205 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00009206 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9207
9208 // Check that all of the elements are integer constants or undefs.
9209 bool AllEltsOk = true;
9210 for (unsigned i = 0; i != 16; ++i) {
9211 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9212 !isa<UndefValue>(Mask->getOperand(i))) {
9213 AllEltsOk = false;
9214 break;
9215 }
9216 }
9217
9218 if (AllEltsOk) {
9219 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00009220 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9221 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009222 Value *Result = UndefValue::get(Op0->getType());
9223
9224 // Only extract each element once.
9225 Value *ExtractedElts[32];
9226 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9227
9228 for (unsigned i = 0; i != 16; ++i) {
9229 if (isa<UndefValue>(Mask->getOperand(i)))
9230 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00009231 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00009232 Idx &= 31; // Match the hardware behavior.
9233
9234 if (ExtractedElts[Idx] == 0) {
9235 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00009236 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009237 InsertNewInstBefore(Elt, CI);
9238 ExtractedElts[Idx] = Elt;
9239 }
9240
9241 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009242 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9243 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009244 InsertNewInstBefore(cast<Instruction>(Result), CI);
9245 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009246 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009247 }
9248 }
9249 break;
9250
Chris Lattnera728ddc2006-01-13 21:28:09 +00009251 case Intrinsic::stackrestore: {
9252 // If the save is right next to the restore, remove the restore. This can
9253 // happen when variable allocas are DCE'd.
9254 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9255 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9256 BasicBlock::iterator BI = SS;
9257 if (&*++BI == II)
9258 return EraseInstFromFunction(CI);
9259 }
9260 }
9261
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009262 // Scan down this block to see if there is another stack restore in the
9263 // same block without an intervening call/alloca.
9264 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009265 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009266 bool CannotRemove = false;
9267 for (++BI; &*BI != TI; ++BI) {
9268 if (isa<AllocaInst>(BI)) {
9269 CannotRemove = true;
9270 break;
9271 }
9272 if (isa<CallInst>(BI)) {
9273 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00009274 CannotRemove = true;
9275 break;
9276 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009277 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00009278 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009279 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009280 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009281
9282 // If the stack restore is in a return/unwind block and if there are no
9283 // allocas or calls between the restore and the return, nuke the restore.
9284 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9285 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009286 break;
9287 }
9288 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009289 }
9290
Chris Lattner8b0ea312006-01-13 20:11:04 +00009291 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009292}
9293
9294// InvokeInst simplification
9295//
9296Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009297 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009298}
9299
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009300/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9301/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009302static bool isSafeToEliminateVarargsCast(const CallSite CS,
9303 const CastInst * const CI,
9304 const TargetData * const TD,
9305 const int ix) {
9306 if (!CI->isLosslessCast())
9307 return false;
9308
9309 // The size of ByVal arguments is derived from the type, so we
9310 // can't change to a type with a different size. If the size were
9311 // passed explicitly we could avoid this check.
9312 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9313 return true;
9314
9315 const Type* SrcTy =
9316 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9317 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9318 if (!SrcTy->isSized() || !DstTy->isSized())
9319 return false;
9320 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9321 return false;
9322 return true;
9323}
9324
Chris Lattnera44d8a22003-10-07 22:32:43 +00009325// visitCallSite - Improvements for call and invoke instructions.
9326//
9327Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009328 bool Changed = false;
9329
9330 // If the callee is a constexpr cast of a function, attempt to move the cast
9331 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009332 if (transformConstExprCastCall(CS)) return 0;
9333
Chris Lattner6c266db2003-10-07 22:54:13 +00009334 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009335
Chris Lattner08b22ec2005-05-13 07:09:09 +00009336 if (Function *CalleeF = dyn_cast<Function>(Callee))
9337 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9338 Instruction *OldCall = CS.getInstruction();
9339 // If the call and callee calling conventions don't match, this call must
9340 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009341 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009342 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9343 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009344 if (!OldCall->use_empty())
9345 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9346 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9347 return EraseInstFromFunction(*OldCall);
9348 return 0;
9349 }
9350
Chris Lattner17be6352004-10-18 02:59:09 +00009351 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9352 // This instruction is not reachable, just remove it. We insert a store to
9353 // undef so that we know that this code is not reachable, despite the fact
9354 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009355 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009356 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009357 CS.getInstruction());
9358
9359 if (!CS.getInstruction()->use_empty())
9360 CS.getInstruction()->
9361 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9362
9363 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9364 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009365 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9366 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009367 }
Chris Lattner17be6352004-10-18 02:59:09 +00009368 return EraseInstFromFunction(*CS.getInstruction());
9369 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009370
Duncan Sandscdb6d922007-09-17 10:26:40 +00009371 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9372 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9373 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9374 return transformCallThroughTrampoline(CS);
9375
Chris Lattner6c266db2003-10-07 22:54:13 +00009376 const PointerType *PTy = cast<PointerType>(Callee->getType());
9377 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9378 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009379 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009380 // See if we can optimize any arguments passed through the varargs area of
9381 // the call.
9382 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009383 E = CS.arg_end(); I != E; ++I, ++ix) {
9384 CastInst *CI = dyn_cast<CastInst>(*I);
9385 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9386 *I = CI->getOperand(0);
9387 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009388 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009389 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009390 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009391
Duncan Sandsf0c33542007-12-19 21:13:37 +00009392 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009393 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009394 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009395 Changed = true;
9396 }
9397
Chris Lattner6c266db2003-10-07 22:54:13 +00009398 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009399}
9400
Chris Lattner9fe38862003-06-19 17:00:31 +00009401// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9402// attempt to move the cast to the arguments of the call/invoke.
9403//
9404bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9405 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9406 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009407 if (CE->getOpcode() != Instruction::BitCast ||
9408 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009409 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009410 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009411 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00009412 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00009413
9414 // Okay, this is a cast from a function to a different type. Unless doing so
9415 // would cause a type conversion of one of our arguments, change this call to
9416 // be a direct call with arguments casted to the appropriate types.
9417 //
9418 const FunctionType *FT = Callee->getFunctionType();
9419 const Type *OldRetTy = Caller->getType();
9420
Devang Patel75e6f022008-03-11 18:04:06 +00009421 if (isa<StructType>(FT->getReturnType()))
9422 return false; // TODO: Handle multiple return values.
9423
Chris Lattnerf78616b2004-01-14 06:06:08 +00009424 // Check to see if we are changing the return type...
9425 if (OldRetTy != FT->getReturnType()) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009426 if (Callee->isDeclaration() &&
Chris Lattner46013f42007-01-06 19:53:32 +00009427 // Conversion is ok if changing from pointer to int of same size.
9428 !(isa<PointerType>(FT->getReturnType()) &&
9429 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00009430 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009431
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009432 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009433 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00009434 FT->getReturnType() != Type::VoidTy &&
9435 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009436 return false; // Cannot transform this return value.
9437
Chris Lattner58d74912008-03-12 17:45:29 +00009438 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9439 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00009440 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9441 return false; // Attribute not compatible with transformed value.
9442 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009443
Chris Lattnerf78616b2004-01-14 06:06:08 +00009444 // If the callsite is an invoke instruction, and the return value is used by
9445 // a PHI node in a successor, we cannot change the return type of the call
9446 // because there is no place to put the cast instruction (without breaking
9447 // the critical edge). Bail out in this case.
9448 if (!Caller->use_empty())
9449 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9450 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9451 UI != E; ++UI)
9452 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9453 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009454 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009455 return false;
9456 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009457
9458 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9459 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009460
Chris Lattner9fe38862003-06-19 17:00:31 +00009461 CallSite::arg_iterator AI = CS.arg_begin();
9462 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9463 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009464 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009465
9466 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009467 return false; // Cannot transform this parameter value.
9468
Chris Lattner58d74912008-03-12 17:45:29 +00009469 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9470 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009471
Reid Spencer3da59db2006-11-27 01:05:10 +00009472 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009473 // Some conversions are safe even if we do not have a body.
9474 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00009475 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00009476 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00009477 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009478 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9479 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00009480 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00009481 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009482 }
9483
9484 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009485 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009486 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009487
Chris Lattner58d74912008-03-12 17:45:29 +00009488 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9489 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009490 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009491 // won't be dropping them. Check that these extra arguments have attributes
9492 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009493 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9494 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009495 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009496 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009497 if (PAttrs & ParamAttr::VarArgsIncompatible)
9498 return false;
9499 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009500
Chris Lattner9fe38862003-06-19 17:00:31 +00009501 // Okay, we decided that this is a safe thing to do: go ahead and start
9502 // inserting cast instructions as necessary...
9503 std::vector<Value*> Args;
9504 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009505 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009506 attrVec.reserve(NumCommonArgs);
9507
9508 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009509 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009510
9511 // If the return value is not being used, the type may not be compatible
9512 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009513 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009514
9515 // Add the new return attributes.
9516 if (RAttrs)
9517 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009518
9519 AI = CS.arg_begin();
9520 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9521 const Type *ParamTy = FT->getParamType(i);
9522 if ((*AI)->getType() == ParamTy) {
9523 Args.push_back(*AI);
9524 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009525 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009526 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009527 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009528 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009529 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009530
9531 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009532 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009533 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009534 }
9535
9536 // If the function takes more arguments than the call was taking, add them
9537 // now...
9538 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9539 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9540
9541 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009542 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009543 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009544 cerr << "WARNING: While resolving call to function '"
9545 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009546 } else {
9547 // Add all of the arguments in their promoted form to the arg list...
9548 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9549 const Type *PTy = getPromotedType((*AI)->getType());
9550 if (PTy != (*AI)->getType()) {
9551 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009552 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9553 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009554 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009555 InsertNewInstBefore(Cast, *Caller);
9556 Args.push_back(Cast);
9557 } else {
9558 Args.push_back(*AI);
9559 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009560
Duncan Sandse1e520f2008-01-13 08:02:44 +00009561 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009562 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009563 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9564 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009565 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009566 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009567
9568 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009569 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009570
Chris Lattner58d74912008-03-12 17:45:29 +00009571 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009572
Chris Lattner9fe38862003-06-19 17:00:31 +00009573 Instruction *NC;
9574 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009575 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009576 Args.begin(), Args.end(),
9577 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009578 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009579 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009580 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009581 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9582 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009583 CallInst *CI = cast<CallInst>(Caller);
9584 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009585 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009586 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009587 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009588 }
9589
Chris Lattner6934a042007-02-11 01:23:03 +00009590 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009591 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009592 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009593 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009594 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009595 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009596 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009597
9598 // If this is an invoke instruction, we should insert it after the first
9599 // non-phi, instruction in the normal successor block.
9600 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009601 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009602 InsertNewInstBefore(NC, *I);
9603 } else {
9604 // Otherwise, it's a call, just insert cast right after the call instr
9605 InsertNewInstBefore(NC, *Caller);
9606 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009607 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009608 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009609 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009610 }
9611 }
9612
9613 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9614 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009615 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009616 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009617 return true;
9618}
9619
Duncan Sandscdb6d922007-09-17 10:26:40 +00009620// transformCallThroughTrampoline - Turn a call to a function created by the
9621// init_trampoline intrinsic into a direct call to the underlying function.
9622//
9623Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9624 Value *Callee = CS.getCalledValue();
9625 const PointerType *PTy = cast<PointerType>(Callee->getType());
9626 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009627 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009628
9629 // If the call already has the 'nest' attribute somewhere then give up -
9630 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009631 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009632 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009633
9634 IntrinsicInst *Tramp =
9635 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9636
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009637 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009638 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9639 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9640
Chris Lattner58d74912008-03-12 17:45:29 +00009641 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9642 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009643 unsigned NestIdx = 1;
9644 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009645 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009646
9647 // Look for a parameter marked with the 'nest' attribute.
9648 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9649 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009650 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009651 // Record the parameter type and any other attributes.
9652 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009653 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009654 break;
9655 }
9656
9657 if (NestTy) {
9658 Instruction *Caller = CS.getInstruction();
9659 std::vector<Value*> NewArgs;
9660 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9661
Chris Lattner58d74912008-03-12 17:45:29 +00009662 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9663 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009664
Duncan Sandscdb6d922007-09-17 10:26:40 +00009665 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009666 // mean appending it. Likewise for attributes.
9667
9668 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009669 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9670 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009671
Duncan Sandscdb6d922007-09-17 10:26:40 +00009672 {
9673 unsigned Idx = 1;
9674 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9675 do {
9676 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009677 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009678 Value *NestVal = Tramp->getOperand(3);
9679 if (NestVal->getType() != NestTy)
9680 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9681 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009682 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009683 }
9684
9685 if (I == E)
9686 break;
9687
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009688 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009689 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009690 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009691 NewAttrs.push_back
9692 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009693
9694 ++Idx, ++I;
9695 } while (1);
9696 }
9697
9698 // The trampoline may have been bitcast to a bogus type (FTy).
9699 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009700 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009701
Duncan Sandscdb6d922007-09-17 10:26:40 +00009702 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009703 NewTypes.reserve(FTy->getNumParams()+1);
9704
Duncan Sandscdb6d922007-09-17 10:26:40 +00009705 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009706 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009707 {
9708 unsigned Idx = 1;
9709 FunctionType::param_iterator I = FTy->param_begin(),
9710 E = FTy->param_end();
9711
9712 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009713 if (Idx == NestIdx)
9714 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009715 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009716
9717 if (I == E)
9718 break;
9719
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009720 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009721 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009722
9723 ++Idx, ++I;
9724 } while (1);
9725 }
9726
9727 // Replace the trampoline call with a direct call. Let the generic
9728 // code sort out any function type mismatches.
9729 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009730 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009731 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9732 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009733 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009734
9735 Instruction *NewCaller;
9736 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009737 NewCaller = InvokeInst::Create(NewCallee,
9738 II->getNormalDest(), II->getUnwindDest(),
9739 NewArgs.begin(), NewArgs.end(),
9740 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009741 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009742 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009743 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009744 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9745 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009746 if (cast<CallInst>(Caller)->isTailCall())
9747 cast<CallInst>(NewCaller)->setTailCall();
9748 cast<CallInst>(NewCaller)->
9749 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009750 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009751 }
9752 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9753 Caller->replaceAllUsesWith(NewCaller);
9754 Caller->eraseFromParent();
9755 RemoveFromWorkList(Caller);
9756 return 0;
9757 }
9758 }
9759
9760 // Replace the trampoline call with a direct call. Since there is no 'nest'
9761 // parameter, there is no need to adjust the argument list. Let the generic
9762 // code sort out any function type mismatches.
9763 Constant *NewCallee =
9764 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9765 CS.setCalledFunction(NewCallee);
9766 return CS.getInstruction();
9767}
9768
Chris Lattner7da52b22006-11-01 04:51:18 +00009769/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9770/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9771/// and a single binop.
9772Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9773 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009774 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9775 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009776 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009777 Value *LHSVal = FirstInst->getOperand(0);
9778 Value *RHSVal = FirstInst->getOperand(1);
9779
9780 const Type *LHSType = LHSVal->getType();
9781 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009782
9783 // Scan to see if all operands are the same opcode, all have one use, and all
9784 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009785 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009786 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009787 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009788 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009789 // types or GEP's with different index types.
9790 I->getOperand(0)->getType() != LHSType ||
9791 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009792 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009793
9794 // If they are CmpInst instructions, check their predicates
9795 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9796 if (cast<CmpInst>(I)->getPredicate() !=
9797 cast<CmpInst>(FirstInst)->getPredicate())
9798 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009799
9800 // Keep track of which operand needs a phi node.
9801 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9802 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009803 }
9804
Chris Lattner53738a42006-11-08 19:42:28 +00009805 // Otherwise, this is safe to transform, determine if it is profitable.
9806
9807 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9808 // Indexes are often folded into load/store instructions, so we don't want to
9809 // hide them behind a phi.
9810 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9811 return 0;
9812
Chris Lattner7da52b22006-11-01 04:51:18 +00009813 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009814 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009815 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009816 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009817 NewLHS = PHINode::Create(LHSType,
9818 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009819 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9820 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009821 InsertNewInstBefore(NewLHS, PN);
9822 LHSVal = NewLHS;
9823 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009824
9825 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009826 NewRHS = PHINode::Create(RHSType,
9827 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009828 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9829 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009830 InsertNewInstBefore(NewRHS, PN);
9831 RHSVal = NewRHS;
9832 }
9833
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009834 // Add all operands to the new PHIs.
9835 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9836 if (NewLHS) {
9837 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9838 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9839 }
9840 if (NewRHS) {
9841 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9842 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9843 }
9844 }
9845
Chris Lattner7da52b22006-11-01 04:51:18 +00009846 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009847 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009848 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009849 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009850 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009851 else {
9852 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009853 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009854 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009855}
9856
Chris Lattner76c73142006-11-01 07:13:54 +00009857/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9858/// of the block that defines it. This means that it must be obvious the value
9859/// of the load is not changed from the point of the load to the end of the
9860/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009861///
9862/// Finally, it is safe, but not profitable, to sink a load targetting a
9863/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9864/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009865static bool isSafeToSinkLoad(LoadInst *L) {
9866 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9867
9868 for (++BBI; BBI != E; ++BBI)
9869 if (BBI->mayWriteToMemory())
9870 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009871
9872 // Check for non-address taken alloca. If not address-taken already, it isn't
9873 // profitable to do this xform.
9874 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9875 bool isAddressTaken = false;
9876 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9877 UI != E; ++UI) {
9878 if (isa<LoadInst>(UI)) continue;
9879 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9880 // If storing TO the alloca, then the address isn't taken.
9881 if (SI->getOperand(1) == AI) continue;
9882 }
9883 isAddressTaken = true;
9884 break;
9885 }
9886
9887 if (!isAddressTaken)
9888 return false;
9889 }
9890
Chris Lattner76c73142006-11-01 07:13:54 +00009891 return true;
9892}
9893
Chris Lattner9fe38862003-06-19 17:00:31 +00009894
Chris Lattnerbac32862004-11-14 19:13:23 +00009895// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9896// operator and they all are only used by the PHI, PHI together their
9897// inputs, and do the operation once, to the result of the PHI.
9898Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9899 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9900
9901 // Scan the instruction, looking for input operations that can be folded away.
9902 // If all input operands to the phi are the same instruction (e.g. a cast from
9903 // the same type or "+42") we can pull the operation through the PHI, reducing
9904 // code size and simplifying code.
9905 Constant *ConstantOp = 0;
9906 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009907 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009908 if (isa<CastInst>(FirstInst)) {
9909 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009910 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009911 // Can fold binop, compare or shift here if the RHS is a constant,
9912 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009913 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009914 if (ConstantOp == 0)
9915 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009916 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9917 isVolatile = LI->isVolatile();
9918 // We can't sink the load if the loaded value could be modified between the
9919 // load and the PHI.
9920 if (LI->getParent() != PN.getIncomingBlock(0) ||
9921 !isSafeToSinkLoad(LI))
9922 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009923 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009924 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009925 return FoldPHIArgBinOpIntoPHI(PN);
9926 // Can't handle general GEPs yet.
9927 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009928 } else {
9929 return 0; // Cannot fold this operation.
9930 }
9931
9932 // Check to see if all arguments are the same operation.
9933 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9934 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9935 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009936 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009937 return 0;
9938 if (CastSrcTy) {
9939 if (I->getOperand(0)->getType() != CastSrcTy)
9940 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009941 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009942 // We can't sink the load if the loaded value could be modified between
9943 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009944 if (LI->isVolatile() != isVolatile ||
9945 LI->getParent() != PN.getIncomingBlock(i) ||
9946 !isSafeToSinkLoad(LI))
9947 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009948
9949 // If the PHI is volatile and its block has multiple successors, sinking
9950 // it would remove a load of the volatile value from the path through the
9951 // other successor.
9952 if (isVolatile &&
9953 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9954 return 0;
9955
9956
Chris Lattnerbac32862004-11-14 19:13:23 +00009957 } else if (I->getOperand(1) != ConstantOp) {
9958 return 0;
9959 }
9960 }
9961
9962 // Okay, they are all the same operation. Create a new PHI node of the
9963 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009964 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9965 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009966 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009967
9968 Value *InVal = FirstInst->getOperand(0);
9969 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009970
9971 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009972 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9973 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9974 if (NewInVal != InVal)
9975 InVal = 0;
9976 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9977 }
9978
9979 Value *PhiVal;
9980 if (InVal) {
9981 // The new PHI unions all of the same values together. This is really
9982 // common, so we handle it intelligently here for compile-time speed.
9983 PhiVal = InVal;
9984 delete NewPN;
9985 } else {
9986 InsertNewInstBefore(NewPN, PN);
9987 PhiVal = NewPN;
9988 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009989
Chris Lattnerbac32862004-11-14 19:13:23 +00009990 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009991 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009992 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009993 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009994 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009995 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009996 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009997 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009998 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9999
10000 // If this was a volatile load that we are merging, make sure to loop through
10001 // and mark all the input loads as non-volatile. If we don't do this, we will
10002 // insert a new volatile load and the old ones will not be deletable.
10003 if (isVolatile)
10004 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10005 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10006
10007 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010008}
Chris Lattnera1be5662002-05-02 17:06:02 +000010009
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010010/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10011/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010012static bool DeadPHICycle(PHINode *PN,
10013 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010014 if (PN->use_empty()) return true;
10015 if (!PN->hasOneUse()) return false;
10016
10017 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010018 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010019 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010020
10021 // Don't scan crazily complex things.
10022 if (PotentiallyDeadPHIs.size() == 16)
10023 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010024
10025 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10026 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010027
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010028 return false;
10029}
10030
Chris Lattnercf5008a2007-11-06 21:52:06 +000010031/// PHIsEqualValue - Return true if this phi node is always equal to
10032/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10033/// z = some value; x = phi (y, z); y = phi (x, z)
10034static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10035 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10036 // See if we already saw this PHI node.
10037 if (!ValueEqualPHIs.insert(PN))
10038 return true;
10039
10040 // Don't scan crazily complex things.
10041 if (ValueEqualPHIs.size() == 16)
10042 return false;
10043
10044 // Scan the operands to see if they are either phi nodes or are equal to
10045 // the value.
10046 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10047 Value *Op = PN->getIncomingValue(i);
10048 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10049 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10050 return false;
10051 } else if (Op != NonPhiInVal)
10052 return false;
10053 }
10054
10055 return true;
10056}
10057
10058
Chris Lattner473945d2002-05-06 18:06:38 +000010059// PHINode simplification
10060//
Chris Lattner7e708292002-06-25 16:13:24 +000010061Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010062 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010063 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010064
Owen Anderson7e057142006-07-10 22:03:18 +000010065 if (Value *V = PN.hasConstantValue())
10066 return ReplaceInstUsesWith(PN, V);
10067
Owen Anderson7e057142006-07-10 22:03:18 +000010068 // If all PHI operands are the same operation, pull them through the PHI,
10069 // reducing code size.
10070 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10071 PN.getIncomingValue(0)->hasOneUse())
10072 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10073 return Result;
10074
10075 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10076 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10077 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010078 if (PN.hasOneUse()) {
10079 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10080 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010081 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010082 PotentiallyDeadPHIs.insert(&PN);
10083 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10084 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10085 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010086
10087 // If this phi has a single use, and if that use just computes a value for
10088 // the next iteration of a loop, delete the phi. This occurs with unused
10089 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10090 // common case here is good because the only other things that catch this
10091 // are induction variable analysis (sometimes) and ADCE, which is only run
10092 // late.
10093 if (PHIUser->hasOneUse() &&
10094 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10095 PHIUser->use_back() == &PN) {
10096 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10097 }
10098 }
Owen Anderson7e057142006-07-10 22:03:18 +000010099
Chris Lattnercf5008a2007-11-06 21:52:06 +000010100 // We sometimes end up with phi cycles that non-obviously end up being the
10101 // same value, for example:
10102 // z = some value; x = phi (y, z); y = phi (x, z)
10103 // where the phi nodes don't necessarily need to be in the same block. Do a
10104 // quick check to see if the PHI node only contains a single non-phi value, if
10105 // so, scan to see if the phi cycle is actually equal to that value.
10106 {
10107 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10108 // Scan for the first non-phi operand.
10109 while (InValNo != NumOperandVals &&
10110 isa<PHINode>(PN.getIncomingValue(InValNo)))
10111 ++InValNo;
10112
10113 if (InValNo != NumOperandVals) {
10114 Value *NonPhiInVal = PN.getOperand(InValNo);
10115
10116 // Scan the rest of the operands to see if there are any conflicts, if so
10117 // there is no need to recursively scan other phis.
10118 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10119 Value *OpVal = PN.getIncomingValue(InValNo);
10120 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10121 break;
10122 }
10123
10124 // If we scanned over all operands, then we have one unique value plus
10125 // phi values. Scan PHI nodes to see if they all merge in each other or
10126 // the value.
10127 if (InValNo == NumOperandVals) {
10128 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10129 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10130 return ReplaceInstUsesWith(PN, NonPhiInVal);
10131 }
10132 }
10133 }
Chris Lattner60921c92003-12-19 05:58:40 +000010134 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010135}
10136
Reid Spencer17212df2006-12-12 09:18:51 +000010137static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10138 Instruction *InsertPoint,
10139 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010140 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10141 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010142 // We must cast correctly to the pointer type. Ensure that we
10143 // sign extend the integer value if it is smaller as this is
10144 // used for address computation.
10145 Instruction::CastOps opcode =
10146 (VTySize < PtrSize ? Instruction::SExt :
10147 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10148 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010149}
10150
Chris Lattnera1be5662002-05-02 17:06:02 +000010151
Chris Lattner7e708292002-06-25 16:13:24 +000010152Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010153 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010154 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010155 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010156 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010157 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010158
Chris Lattnere87597f2004-10-16 18:11:37 +000010159 if (isa<UndefValue>(GEP.getOperand(0)))
10160 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10161
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010162 bool HasZeroPointerIndex = false;
10163 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10164 HasZeroPointerIndex = C->isNullValue();
10165
10166 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010167 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010168
Chris Lattner28977af2004-04-05 01:30:19 +000010169 // Eliminate unneeded casts for indices.
10170 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010171
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010172 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010173 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010174 if (isa<SequentialType>(*GTI)) {
10175 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010176 if (CI->getOpcode() == Instruction::ZExt ||
10177 CI->getOpcode() == Instruction::SExt) {
10178 const Type *SrcTy = CI->getOperand(0)->getType();
10179 // We can eliminate a cast from i32 to i64 iff the target
10180 // is a 32-bit pointer target.
10181 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10182 MadeChange = true;
10183 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +000010184 }
10185 }
10186 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010187 // If we are using a wider index than needed for this platform, shrink it
10188 // to what we need. If the incoming value needs a cast instruction,
10189 // insert it. This explicit cast can make subsequent optimizations more
10190 // obvious.
10191 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010192 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010193 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010194 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +000010195 MadeChange = true;
10196 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010197 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10198 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010199 GEP.setOperand(i, Op);
10200 MadeChange = true;
10201 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010202 }
Chris Lattner28977af2004-04-05 01:30:19 +000010203 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010204 }
Chris Lattner28977af2004-04-05 01:30:19 +000010205 if (MadeChange) return &GEP;
10206
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010207 // If this GEP instruction doesn't move the pointer, and if the input operand
10208 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10209 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +000010210 if (GEP.hasAllZeroIndices()) {
10211 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10212 // If the bitcast is of an allocation, and the allocation will be
10213 // converted to match the type of the cast, don't touch this.
10214 if (isa<AllocationInst>(BCI->getOperand(0))) {
10215 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +000010216 if (Instruction *I = visitBitCast(*BCI)) {
10217 if (I != BCI) {
10218 I->takeName(BCI);
10219 BCI->getParent()->getInstList().insert(BCI, I);
10220 ReplaceInstUsesWith(*BCI, I);
10221 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010222 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +000010223 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010224 }
10225 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10226 }
10227 }
10228
Chris Lattner90ac28c2002-08-02 19:29:35 +000010229 // Combine Indices - If the source pointer to this getelementptr instruction
10230 // is a getelementptr instruction, combine the indices of the two
10231 // getelementptr instructions into a single instruction.
10232 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010233 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010234 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010235 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010236
10237 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010238 // Note that if our source is a gep chain itself that we wait for that
10239 // chain to be resolved before we perform this transformation. This
10240 // avoids us creating a TON of code in some cases.
10241 //
10242 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10243 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10244 return 0; // Wait until our source is folded to completion.
10245
Chris Lattner72588fc2007-02-15 22:48:32 +000010246 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010247
10248 // Find out whether the last index in the source GEP is a sequential idx.
10249 bool EndsWithSequential = false;
10250 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10251 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010252 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010253
Chris Lattner90ac28c2002-08-02 19:29:35 +000010254 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010255 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010256 // Replace: gep (gep %P, long B), long A, ...
10257 // With: T = long A+B; gep %P, T, ...
10258 //
Chris Lattner620ce142004-05-07 22:09:22 +000010259 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010260 if (SO1 == Constant::getNullValue(SO1->getType())) {
10261 Sum = GO1;
10262 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10263 Sum = SO1;
10264 } else {
10265 // If they aren't the same type, convert both to an integer of the
10266 // target's pointer size.
10267 if (SO1->getType() != GO1->getType()) {
10268 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010269 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010270 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010271 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010272 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010273 unsigned PS = TD->getPointerSizeInBits();
10274 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010275 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010276 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010277
Duncan Sands514ab342007-11-01 20:53:16 +000010278 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010279 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010280 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010281 } else {
10282 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010283 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10284 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010285 }
10286 }
10287 }
Chris Lattner620ce142004-05-07 22:09:22 +000010288 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10289 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10290 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010291 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010292 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010293 }
Chris Lattner28977af2004-04-05 01:30:19 +000010294 }
Chris Lattner620ce142004-05-07 22:09:22 +000010295
10296 // Recycle the GEP we already have if possible.
10297 if (SrcGEPOperands.size() == 2) {
10298 GEP.setOperand(0, SrcGEPOperands[0]);
10299 GEP.setOperand(1, Sum);
10300 return &GEP;
10301 } else {
10302 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10303 SrcGEPOperands.end()-1);
10304 Indices.push_back(Sum);
10305 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10306 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010307 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010308 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010309 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010310 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010311 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10312 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010313 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10314 }
10315
10316 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010317 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10318 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010319
Chris Lattner620ce142004-05-07 22:09:22 +000010320 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010321 // GEP of global variable. If all of the indices for this GEP are
10322 // constants, we can promote this to a constexpr instead of an instruction.
10323
10324 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010325 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010326 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10327 for (; I != E && isa<Constant>(*I); ++I)
10328 Indices.push_back(cast<Constant>(*I));
10329
10330 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010331 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10332 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010333
10334 // Replace all uses of the GEP with the new constexpr...
10335 return ReplaceInstUsesWith(GEP, CE);
10336 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010337 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010338 if (!isa<PointerType>(X->getType())) {
10339 // Not interesting. Source pointer must be a cast from pointer.
10340 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010341 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10342 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010343 //
10344 // This occurs when the program declares an array extern like "int X[];"
10345 //
10346 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10347 const PointerType *XTy = cast<PointerType>(X->getType());
10348 if (const ArrayType *XATy =
10349 dyn_cast<ArrayType>(XTy->getElementType()))
10350 if (const ArrayType *CATy =
10351 dyn_cast<ArrayType>(CPTy->getElementType()))
10352 if (CATy->getElementType() == XATy->getElementType()) {
10353 // At this point, we know that the cast source type is a pointer
10354 // to an array of the same type as the destination pointer
10355 // array. Because the array type is never stepped over (there
10356 // is a leading zero) we can fold the cast into this GEP.
10357 GEP.setOperand(0, X);
10358 return &GEP;
10359 }
10360 } else if (GEP.getNumOperands() == 2) {
10361 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010362 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10363 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010364 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10365 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10366 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +000010367 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10368 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010369 Value *Idx[2];
10370 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10371 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010372 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010373 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010374 // V and GEP are both pointer types --> BitCast
10375 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010376 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010377
10378 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010379 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010380 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010381 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010382
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010383 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010384 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +000010385 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010386
10387 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10388 // allow either a mul, shift, or constant here.
10389 Value *NewIdx = 0;
10390 ConstantInt *Scale = 0;
10391 if (ArrayEltSize == 1) {
10392 NewIdx = GEP.getOperand(1);
10393 Scale = ConstantInt::get(NewIdx->getType(), 1);
10394 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010395 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010396 Scale = CI;
10397 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10398 if (Inst->getOpcode() == Instruction::Shl &&
10399 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010400 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10401 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10402 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010403 NewIdx = Inst->getOperand(0);
10404 } else if (Inst->getOpcode() == Instruction::Mul &&
10405 isa<ConstantInt>(Inst->getOperand(1))) {
10406 Scale = cast<ConstantInt>(Inst->getOperand(1));
10407 NewIdx = Inst->getOperand(0);
10408 }
10409 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010410
Chris Lattner7835cdd2005-09-13 18:36:04 +000010411 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010412 // out, perform the transformation. Note, we don't know whether Scale is
10413 // signed or not. We'll use unsigned version of division/modulo
10414 // operation after making sure Scale doesn't have the sign bit set.
10415 if (Scale && Scale->getSExtValue() >= 0LL &&
10416 Scale->getZExtValue() % ArrayEltSize == 0) {
10417 Scale = ConstantInt::get(Scale->getType(),
10418 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010419 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010420 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010421 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010422 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010423 NewIdx = InsertNewInstBefore(Sc, GEP);
10424 }
10425
10426 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010427 Value *Idx[2];
10428 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10429 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010430 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010431 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010432 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10433 // The NewGEP must be pointer typed, so must the old one -> BitCast
10434 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010435 }
10436 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010437 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010438 }
10439
Chris Lattner8a2a3112001-12-14 16:52:21 +000010440 return 0;
10441}
10442
Chris Lattner0864acf2002-11-04 16:18:53 +000010443Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10444 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010445 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010446 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10447 const Type *NewTy =
10448 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010449 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010450
10451 // Create and insert the replacement instruction...
10452 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010453 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010454 else {
10455 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010456 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010457 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010458
10459 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010460
Chris Lattner0864acf2002-11-04 16:18:53 +000010461 // Scan to the end of the allocation instructions, to skip over a block of
10462 // allocas if possible...
10463 //
10464 BasicBlock::iterator It = New;
10465 while (isa<AllocationInst>(*It)) ++It;
10466
10467 // Now that I is pointing to the first non-allocation-inst in the block,
10468 // insert our getelementptr instruction...
10469 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010470 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010471 Value *Idx[2];
10472 Idx[0] = NullIdx;
10473 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010474 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10475 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010476
10477 // Now make everything use the getelementptr instead of the original
10478 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010479 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010480 } else if (isa<UndefValue>(AI.getArraySize())) {
10481 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010482 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010483 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010484
10485 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10486 // Note that we only do this for alloca's, because malloc should allocate and
10487 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010488 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010489 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010490 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10491
Chris Lattner0864acf2002-11-04 16:18:53 +000010492 return 0;
10493}
10494
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010495Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10496 Value *Op = FI.getOperand(0);
10497
Chris Lattner17be6352004-10-18 02:59:09 +000010498 // free undef -> unreachable.
10499 if (isa<UndefValue>(Op)) {
10500 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010501 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010502 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010503 return EraseInstFromFunction(FI);
10504 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010505
Chris Lattner6160e852004-02-28 04:57:37 +000010506 // If we have 'free null' delete the instruction. This can happen in stl code
10507 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010508 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010509 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010510
10511 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10512 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10513 FI.setOperand(0, CI->getOperand(0));
10514 return &FI;
10515 }
10516
10517 // Change free (gep X, 0,0,0,0) into free(X)
10518 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10519 if (GEPI->hasAllZeroIndices()) {
10520 AddToWorkList(GEPI);
10521 FI.setOperand(0, GEPI->getOperand(0));
10522 return &FI;
10523 }
10524 }
10525
10526 // Change free(malloc) into nothing, if the malloc has a single use.
10527 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10528 if (MI->hasOneUse()) {
10529 EraseInstFromFunction(FI);
10530 return EraseInstFromFunction(*MI);
10531 }
Chris Lattner6160e852004-02-28 04:57:37 +000010532
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010533 return 0;
10534}
10535
10536
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010537/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010538static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010539 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010540 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010541 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010542
Devang Patel99db6ad2007-10-18 19:52:32 +000010543 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10544 // Instead of loading constant c string, use corresponding integer value
10545 // directly if string length is small enough.
10546 const std::string &Str = CE->getOperand(0)->getStringValue();
10547 if (!Str.empty()) {
10548 unsigned len = Str.length();
10549 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10550 unsigned numBits = Ty->getPrimitiveSizeInBits();
10551 // Replace LI with immediate integer store.
10552 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010553 APInt StrVal(numBits, 0);
10554 APInt SingleChar(numBits, 0);
10555 if (TD->isLittleEndian()) {
10556 for (signed i = len-1; i >= 0; i--) {
10557 SingleChar = (uint64_t) Str[i];
10558 StrVal = (StrVal << 8) | SingleChar;
10559 }
10560 } else {
10561 for (unsigned i = 0; i < len; i++) {
10562 SingleChar = (uint64_t) Str[i];
10563 StrVal = (StrVal << 8) | SingleChar;
10564 }
10565 // Append NULL at the end.
10566 SingleChar = 0;
10567 StrVal = (StrVal << 8) | SingleChar;
10568 }
10569 Value *NL = ConstantInt::get(StrVal);
10570 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010571 }
10572 }
10573 }
10574
Chris Lattnerb89e0712004-07-13 01:49:43 +000010575 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010576 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010577 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010578
Reid Spencer42230162007-01-22 05:51:25 +000010579 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010580 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010581 // If the source is an array, the code below will not succeed. Check to
10582 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10583 // constants.
10584 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10585 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10586 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010587 Value *Idxs[2];
10588 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10589 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010590 SrcTy = cast<PointerType>(CastOp->getType());
10591 SrcPTy = SrcTy->getElementType();
10592 }
10593
Reid Spencer42230162007-01-22 05:51:25 +000010594 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010595 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010596 // Do not allow turning this into a load of an integer, which is then
10597 // casted to a pointer, this pessimizes pointer analysis a lot.
10598 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010599 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10600 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010601
Chris Lattnerf9527852005-01-31 04:50:46 +000010602 // Okay, we are casting from one integer or pointer type to another of
10603 // the same size. Instead of casting the pointer before the load, cast
10604 // the result of the loaded value.
10605 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10606 CI->getName(),
10607 LI.isVolatile()),LI);
10608 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010609 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010610 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010611 }
10612 }
10613 return 0;
10614}
10615
Chris Lattnerc10aced2004-09-19 18:43:46 +000010616/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010617/// from this value cannot trap. If it is not obviously safe to load from the
10618/// specified pointer, we do a quick local scan of the basic block containing
10619/// ScanFrom, to determine if the address is already accessed.
10620static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010621 // If it is an alloca it is always safe to load from.
10622 if (isa<AllocaInst>(V)) return true;
10623
Duncan Sands46318cd2007-09-19 10:25:38 +000010624 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010625 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010626 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010627 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010628
10629 // Otherwise, be a little bit agressive by scanning the local block where we
10630 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010631 // from/to. If so, the previous load or store would have already trapped,
10632 // so there is no harm doing an extra load (also, CSE will later eliminate
10633 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010634 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10635
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010636 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010637 --BBI;
10638
10639 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10640 if (LI->getOperand(0) == V) return true;
10641 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10642 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010643
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010644 }
Chris Lattner8a375202004-09-19 19:18:10 +000010645 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010646}
10647
Chris Lattner8d2e8882007-08-11 18:48:48 +000010648/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10649/// until we find the underlying object a pointer is referring to or something
10650/// we don't understand. Note that the returned pointer may be offset from the
10651/// input, because we ignore GEP indices.
10652static Value *GetUnderlyingObject(Value *Ptr) {
10653 while (1) {
10654 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10655 if (CE->getOpcode() == Instruction::BitCast ||
10656 CE->getOpcode() == Instruction::GetElementPtr)
10657 Ptr = CE->getOperand(0);
10658 else
10659 return Ptr;
10660 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10661 Ptr = BCI->getOperand(0);
10662 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10663 Ptr = GEP->getOperand(0);
10664 } else {
10665 return Ptr;
10666 }
10667 }
10668}
10669
Chris Lattner833b8a42003-06-26 05:06:25 +000010670Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10671 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010672
Dan Gohman9941f742007-07-20 16:34:21 +000010673 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010674 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10675 if (KnownAlign >
10676 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10677 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010678 LI.setAlignment(KnownAlign);
10679
Chris Lattner37366c12005-05-01 04:24:53 +000010680 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010681 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010682 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010683 return Res;
10684
10685 // None of the following transforms are legal for volatile loads.
10686 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010687
Chris Lattner62f254d2005-09-12 22:00:15 +000010688 if (&LI.getParent()->front() != &LI) {
10689 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010690 // If the instruction immediately before this is a store to the same
10691 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010692 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10693 if (SI->getOperand(1) == LI.getOperand(0))
10694 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010695 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10696 if (LIB->getOperand(0) == LI.getOperand(0))
10697 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010698 }
Chris Lattner37366c12005-05-01 04:24:53 +000010699
Christopher Lambb15147e2007-12-29 07:56:53 +000010700 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10701 const Value *GEPI0 = GEPI->getOperand(0);
10702 // TODO: Consider a target hook for valid address spaces for this xform.
10703 if (isa<ConstantPointerNull>(GEPI0) &&
10704 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010705 // Insert a new store to null instruction before the load to indicate
10706 // that this code is not reachable. We do this instead of inserting
10707 // an unreachable instruction directly because we cannot modify the
10708 // CFG.
10709 new StoreInst(UndefValue::get(LI.getType()),
10710 Constant::getNullValue(Op->getType()), &LI);
10711 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10712 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010713 }
Chris Lattner37366c12005-05-01 04:24:53 +000010714
Chris Lattnere87597f2004-10-16 18:11:37 +000010715 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010716 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010717 // TODO: Consider a target hook for valid address spaces for this xform.
10718 if (isa<UndefValue>(C) || (C->isNullValue() &&
10719 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010720 // Insert a new store to null instruction before the load to indicate that
10721 // this code is not reachable. We do this instead of inserting an
10722 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010723 new StoreInst(UndefValue::get(LI.getType()),
10724 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010725 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010726 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010727
Chris Lattnere87597f2004-10-16 18:11:37 +000010728 // Instcombine load (constant global) into the value loaded.
10729 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010730 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010731 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010732
Chris Lattnere87597f2004-10-16 18:11:37 +000010733 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010734 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010735 if (CE->getOpcode() == Instruction::GetElementPtr) {
10736 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010737 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010738 if (Constant *V =
10739 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010740 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010741 if (CE->getOperand(0)->isNullValue()) {
10742 // Insert a new store to null instruction before the load to indicate
10743 // that this code is not reachable. We do this instead of inserting
10744 // an unreachable instruction directly because we cannot modify the
10745 // CFG.
10746 new StoreInst(UndefValue::get(LI.getType()),
10747 Constant::getNullValue(Op->getType()), &LI);
10748 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10749 }
10750
Reid Spencer3da59db2006-11-27 01:05:10 +000010751 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010752 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010753 return Res;
10754 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010755 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010756 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010757
10758 // If this load comes from anywhere in a constant global, and if the global
10759 // is all undef or zero, we know what it loads.
10760 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10761 if (GV->isConstant() && GV->hasInitializer()) {
10762 if (GV->getInitializer()->isNullValue())
10763 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10764 else if (isa<UndefValue>(GV->getInitializer()))
10765 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10766 }
10767 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010768
Chris Lattner37366c12005-05-01 04:24:53 +000010769 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010770 // Change select and PHI nodes to select values instead of addresses: this
10771 // helps alias analysis out a lot, allows many others simplifications, and
10772 // exposes redundancy in the code.
10773 //
10774 // Note that we cannot do the transformation unless we know that the
10775 // introduced loads cannot trap! Something like this is valid as long as
10776 // the condition is always false: load (select bool %C, int* null, int* %G),
10777 // but it would not be valid if we transformed it to load from null
10778 // unconditionally.
10779 //
10780 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10781 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010782 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10783 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010784 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010785 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010786 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010787 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010788 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010789 }
10790
Chris Lattner684fe212004-09-23 15:46:00 +000010791 // load (select (cond, null, P)) -> load P
10792 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10793 if (C->isNullValue()) {
10794 LI.setOperand(0, SI->getOperand(2));
10795 return &LI;
10796 }
10797
10798 // load (select (cond, P, null)) -> load P
10799 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10800 if (C->isNullValue()) {
10801 LI.setOperand(0, SI->getOperand(1));
10802 return &LI;
10803 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010804 }
10805 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010806 return 0;
10807}
10808
Reid Spencer55af2b52007-01-19 21:20:31 +000010809/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010810/// when possible.
10811static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10812 User *CI = cast<User>(SI.getOperand(1));
10813 Value *CastOp = CI->getOperand(0);
10814
10815 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10816 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10817 const Type *SrcPTy = SrcTy->getElementType();
10818
Reid Spencer42230162007-01-22 05:51:25 +000010819 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010820 // If the source is an array, the code below will not succeed. Check to
10821 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10822 // constants.
10823 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10824 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10825 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010826 Value* Idxs[2];
10827 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10828 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010829 SrcTy = cast<PointerType>(CastOp->getType());
10830 SrcPTy = SrcTy->getElementType();
10831 }
10832
Reid Spencer67f827c2007-01-20 23:35:48 +000010833 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10834 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10835 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010836
10837 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010838 // the same size. Instead of casting the pointer before
10839 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010840 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010841 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010842 Instruction::CastOps opcode = Instruction::BitCast;
10843 const Type* CastSrcTy = SIOp0->getType();
10844 const Type* CastDstTy = SrcPTy;
10845 if (isa<PointerType>(CastDstTy)) {
10846 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010847 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010848 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010849 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010850 opcode = Instruction::PtrToInt;
10851 }
10852 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010853 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010854 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010855 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010856 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010857 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010858 return new StoreInst(NewCast, CastOp);
10859 }
10860 }
10861 }
10862 return 0;
10863}
10864
Chris Lattner2f503e62005-01-31 05:36:43 +000010865Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10866 Value *Val = SI.getOperand(0);
10867 Value *Ptr = SI.getOperand(1);
10868
10869 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010870 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010871 ++NumCombined;
10872 return 0;
10873 }
Chris Lattner836692d2007-01-15 06:51:56 +000010874
10875 // If the RHS is an alloca with a single use, zapify the store, making the
10876 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010877 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010878 if (isa<AllocaInst>(Ptr)) {
10879 EraseInstFromFunction(SI);
10880 ++NumCombined;
10881 return 0;
10882 }
10883
10884 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10885 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10886 GEP->getOperand(0)->hasOneUse()) {
10887 EraseInstFromFunction(SI);
10888 ++NumCombined;
10889 return 0;
10890 }
10891 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010892
Dan Gohman9941f742007-07-20 16:34:21 +000010893 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010894 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10895 if (KnownAlign >
10896 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10897 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010898 SI.setAlignment(KnownAlign);
10899
Chris Lattner9ca96412006-02-08 03:25:32 +000010900 // Do really simple DSE, to catch cases where there are several consequtive
10901 // stores to the same location, separated by a few arithmetic operations. This
10902 // situation often occurs with bitfield accesses.
10903 BasicBlock::iterator BBI = &SI;
10904 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10905 --ScanInsts) {
10906 --BBI;
10907
10908 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10909 // Prev store isn't volatile, and stores to the same location?
10910 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10911 ++NumDeadStore;
10912 ++BBI;
10913 EraseInstFromFunction(*PrevSI);
10914 continue;
10915 }
10916 break;
10917 }
10918
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010919 // If this is a load, we have to stop. However, if the loaded value is from
10920 // the pointer we're loading and is producing the pointer we're storing,
10921 // then *this* store is dead (X = load P; store X -> P).
10922 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010923 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010924 EraseInstFromFunction(SI);
10925 ++NumCombined;
10926 return 0;
10927 }
10928 // Otherwise, this is a load from some other location. Stores before it
10929 // may not be dead.
10930 break;
10931 }
10932
Chris Lattner9ca96412006-02-08 03:25:32 +000010933 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010934 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010935 break;
10936 }
10937
10938
10939 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010940
10941 // store X, null -> turns into 'unreachable' in SimplifyCFG
10942 if (isa<ConstantPointerNull>(Ptr)) {
10943 if (!isa<UndefValue>(Val)) {
10944 SI.setOperand(0, UndefValue::get(Val->getType()));
10945 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010946 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010947 ++NumCombined;
10948 }
10949 return 0; // Do not modify these!
10950 }
10951
10952 // store undef, Ptr -> noop
10953 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010954 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010955 ++NumCombined;
10956 return 0;
10957 }
10958
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010959 // If the pointer destination is a cast, see if we can fold the cast into the
10960 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010961 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010962 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10963 return Res;
10964 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010965 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010966 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10967 return Res;
10968
Chris Lattner408902b2005-09-12 23:23:25 +000010969
10970 // If this store is the last instruction in the basic block, and if the block
10971 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010972 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010973 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010974 if (BI->isUnconditional())
10975 if (SimplifyStoreAtEndOfBlock(SI))
10976 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010977
Chris Lattner2f503e62005-01-31 05:36:43 +000010978 return 0;
10979}
10980
Chris Lattner3284d1f2007-04-15 00:07:55 +000010981/// SimplifyStoreAtEndOfBlock - Turn things like:
10982/// if () { *P = v1; } else { *P = v2 }
10983/// into a phi node with a store in the successor.
10984///
Chris Lattner31755a02007-04-15 01:02:18 +000010985/// Simplify things like:
10986/// *P = v1; if () { *P = v2; }
10987/// into a phi node with a store in the successor.
10988///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010989bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10990 BasicBlock *StoreBB = SI.getParent();
10991
10992 // Check to see if the successor block has exactly two incoming edges. If
10993 // so, see if the other predecessor contains a store to the same location.
10994 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010995 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010996
10997 // Determine whether Dest has exactly two predecessors and, if so, compute
10998 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010999 pred_iterator PI = pred_begin(DestBB);
11000 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011001 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011002 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011003 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011004 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011005 return false;
11006
11007 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011008 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011009 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011010 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011011 }
Chris Lattner31755a02007-04-15 01:02:18 +000011012 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011013 return false;
11014
11015
Chris Lattner31755a02007-04-15 01:02:18 +000011016 // Verify that the other block ends in a branch and is not otherwise empty.
11017 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011018 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011019 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011020 return false;
11021
Chris Lattner31755a02007-04-15 01:02:18 +000011022 // If the other block ends in an unconditional branch, check for the 'if then
11023 // else' case. there is an instruction before the branch.
11024 StoreInst *OtherStore = 0;
11025 if (OtherBr->isUnconditional()) {
11026 // If this isn't a store, or isn't a store to the same location, bail out.
11027 --BBI;
11028 OtherStore = dyn_cast<StoreInst>(BBI);
11029 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11030 return false;
11031 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011032 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011033 // destinations is StoreBB, then we have the if/then case.
11034 if (OtherBr->getSuccessor(0) != StoreBB &&
11035 OtherBr->getSuccessor(1) != StoreBB)
11036 return false;
11037
11038 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011039 // if/then triangle. See if there is a store to the same ptr as SI that
11040 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011041 for (;; --BBI) {
11042 // Check to see if we find the matching store.
11043 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11044 if (OtherStore->getOperand(1) != SI.getOperand(1))
11045 return false;
11046 break;
11047 }
Chris Lattnerd717c182007-05-05 22:32:24 +000011048 // If we find something that may be using the stored value, or if we run
11049 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000011050 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11051 BBI == OtherBB->begin())
11052 return false;
11053 }
11054
11055 // In order to eliminate the store in OtherBr, we have to
11056 // make sure nothing reads the stored value in StoreBB.
11057 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11058 // FIXME: This should really be AA driven.
11059 if (isa<LoadInst>(I) || I->mayWriteToMemory())
11060 return false;
11061 }
11062 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011063
Chris Lattner31755a02007-04-15 01:02:18 +000011064 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011065 Value *MergedVal = OtherStore->getOperand(0);
11066 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011067 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011068 PN->reserveOperandSpace(2);
11069 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011070 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11071 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011072 }
11073
11074 // Advance to a place where it is safe to insert the new store and
11075 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011076 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011077 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11078 OtherStore->isVolatile()), *BBI);
11079
11080 // Nuke the old stores.
11081 EraseInstFromFunction(SI);
11082 EraseInstFromFunction(*OtherStore);
11083 ++NumCombined;
11084 return true;
11085}
11086
Chris Lattner2f503e62005-01-31 05:36:43 +000011087
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011088Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11089 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011090 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011091 BasicBlock *TrueDest;
11092 BasicBlock *FalseDest;
11093 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11094 !isa<Constant>(X)) {
11095 // Swap Destinations and condition...
11096 BI.setCondition(X);
11097 BI.setSuccessor(0, FalseDest);
11098 BI.setSuccessor(1, TrueDest);
11099 return &BI;
11100 }
11101
Reid Spencere4d87aa2006-12-23 06:05:41 +000011102 // Cannonicalize fcmp_one -> fcmp_oeq
11103 FCmpInst::Predicate FPred; Value *Y;
11104 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11105 TrueDest, FalseDest)))
11106 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11107 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11108 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011109 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011110 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11111 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011112 // Swap Destinations and condition...
11113 BI.setCondition(NewSCC);
11114 BI.setSuccessor(0, FalseDest);
11115 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011116 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011117 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011118 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011119 return &BI;
11120 }
11121
11122 // Cannonicalize icmp_ne -> icmp_eq
11123 ICmpInst::Predicate IPred;
11124 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11125 TrueDest, FalseDest)))
11126 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11127 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11128 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11129 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011130 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011131 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11132 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011133 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011134 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011135 BI.setSuccessor(0, FalseDest);
11136 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011137 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011138 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011139 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011140 return &BI;
11141 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011142
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011143 return 0;
11144}
Chris Lattner0864acf2002-11-04 16:18:53 +000011145
Chris Lattner46238a62004-07-03 00:26:11 +000011146Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11147 Value *Cond = SI.getCondition();
11148 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11149 if (I->getOpcode() == Instruction::Add)
11150 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11151 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11152 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011153 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011154 AddRHS));
11155 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011156 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011157 return &SI;
11158 }
11159 }
11160 return 0;
11161}
11162
Chris Lattner220b0cf2006-03-05 00:22:33 +000011163/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11164/// is to leave as a vector operation.
11165static bool CheapToScalarize(Value *V, bool isConstant) {
11166 if (isa<ConstantAggregateZero>(V))
11167 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011168 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011169 if (isConstant) return true;
11170 // If all elts are the same, we can extract.
11171 Constant *Op0 = C->getOperand(0);
11172 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11173 if (C->getOperand(i) != Op0)
11174 return false;
11175 return true;
11176 }
11177 Instruction *I = dyn_cast<Instruction>(V);
11178 if (!I) return false;
11179
11180 // Insert element gets simplified to the inserted element or is deleted if
11181 // this is constant idx extract element and its a constant idx insertelt.
11182 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11183 isa<ConstantInt>(I->getOperand(2)))
11184 return true;
11185 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11186 return true;
11187 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11188 if (BO->hasOneUse() &&
11189 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11190 CheapToScalarize(BO->getOperand(1), isConstant)))
11191 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011192 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11193 if (CI->hasOneUse() &&
11194 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11195 CheapToScalarize(CI->getOperand(1), isConstant)))
11196 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011197
11198 return false;
11199}
11200
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011201/// Read and decode a shufflevector mask.
11202///
11203/// It turns undef elements into values that are larger than the number of
11204/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011205static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11206 unsigned NElts = SVI->getType()->getNumElements();
11207 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11208 return std::vector<unsigned>(NElts, 0);
11209 if (isa<UndefValue>(SVI->getOperand(2)))
11210 return std::vector<unsigned>(NElts, 2*NElts);
11211
11212 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011213 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000011214 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11215 if (isa<UndefValue>(CP->getOperand(i)))
11216 Result.push_back(NElts*2); // undef -> 8
11217 else
Reid Spencerb83eb642006-10-20 07:07:24 +000011218 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011219 return Result;
11220}
11221
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011222/// FindScalarElement - Given a vector and an element number, see if the scalar
11223/// value is already around as a register, for example if it were inserted then
11224/// extracted from the vector.
11225static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011226 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11227 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011228 unsigned Width = PTy->getNumElements();
11229 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011230 return UndefValue::get(PTy->getElementType());
11231
11232 if (isa<UndefValue>(V))
11233 return UndefValue::get(PTy->getElementType());
11234 else if (isa<ConstantAggregateZero>(V))
11235 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011236 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011237 return CP->getOperand(EltNo);
11238 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11239 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011240 if (!isa<ConstantInt>(III->getOperand(2)))
11241 return 0;
11242 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011243
11244 // If this is an insert to the element we are looking for, return the
11245 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011246 if (EltNo == IIElt)
11247 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011248
11249 // Otherwise, the insertelement doesn't modify the value, recurse on its
11250 // vector input.
11251 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011252 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000011253 unsigned InEl = getShuffleMask(SVI)[EltNo];
11254 if (InEl < Width)
11255 return FindScalarElement(SVI->getOperand(0), InEl);
11256 else if (InEl < Width*2)
11257 return FindScalarElement(SVI->getOperand(1), InEl - Width);
11258 else
11259 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011260 }
11261
11262 // Otherwise, we don't know.
11263 return 0;
11264}
11265
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011266Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011267
Dan Gohman07a96762007-07-16 14:29:03 +000011268 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011269 if (isa<UndefValue>(EI.getOperand(0)))
11270 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11271
Dan Gohman07a96762007-07-16 14:29:03 +000011272 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011273 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11274 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11275
Reid Spencer9d6565a2007-02-15 02:26:10 +000011276 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000011277 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011278 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000011279 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011280 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011281 if (C->getOperand(i) != op0) {
11282 op0 = 0;
11283 break;
11284 }
11285 if (op0)
11286 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011287 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011288
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011289 // If extracting a specified index from the vector, see if we can recursively
11290 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011291 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011292 unsigned IndexVal = IdxC->getZExtValue();
11293 unsigned VectorWidth =
11294 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11295
11296 // If this is extracting an invalid index, turn this into undef, to avoid
11297 // crashing the code below.
11298 if (IndexVal >= VectorWidth)
11299 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11300
Chris Lattner867b99f2006-10-05 06:55:50 +000011301 // This instruction only demands the single element from the input vector.
11302 // If the input vector has a single use, simplify it based on this use
11303 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011304 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011305 uint64_t UndefElts;
11306 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011307 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011308 UndefElts)) {
11309 EI.setOperand(0, V);
11310 return &EI;
11311 }
11312 }
11313
Reid Spencerb83eb642006-10-20 07:07:24 +000011314 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011315 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011316
11317 // If the this extractelement is directly using a bitcast from a vector of
11318 // the same number of elements, see if we can find the source element from
11319 // it. In this case, we will end up needing to bitcast the scalars.
11320 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11321 if (const VectorType *VT =
11322 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11323 if (VT->getNumElements() == VectorWidth)
11324 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11325 return new BitCastInst(Elt, EI.getType());
11326 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011327 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011328
Chris Lattner73fa49d2006-05-25 22:53:38 +000011329 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011330 if (I->hasOneUse()) {
11331 // Push extractelement into predecessor operation if legal and
11332 // profitable to do so
11333 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011334 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11335 if (CheapToScalarize(BO, isConstantElt)) {
11336 ExtractElementInst *newEI0 =
11337 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11338 EI.getName()+".lhs");
11339 ExtractElementInst *newEI1 =
11340 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11341 EI.getName()+".rhs");
11342 InsertNewInstBefore(newEI0, EI);
11343 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011344 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011345 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011346 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011347 unsigned AS =
11348 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011349 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11350 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011351 GetElementPtrInst *GEP =
11352 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011353 InsertNewInstBefore(GEP, EI);
11354 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011355 }
11356 }
11357 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11358 // Extracting the inserted element?
11359 if (IE->getOperand(2) == EI.getOperand(1))
11360 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11361 // If the inserted and extracted elements are constants, they must not
11362 // be the same value, extract from the pre-inserted value instead.
11363 if (isa<Constant>(IE->getOperand(2)) &&
11364 isa<Constant>(EI.getOperand(1))) {
11365 AddUsesToWorkList(EI);
11366 EI.setOperand(0, IE->getOperand(0));
11367 return &EI;
11368 }
11369 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11370 // If this is extracting an element from a shufflevector, figure out where
11371 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011372 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11373 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011374 Value *Src;
11375 if (SrcIdx < SVI->getType()->getNumElements())
11376 Src = SVI->getOperand(0);
11377 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11378 SrcIdx -= SVI->getType()->getNumElements();
11379 Src = SVI->getOperand(1);
11380 } else {
11381 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011382 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011383 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011384 }
11385 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011386 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011387 return 0;
11388}
11389
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011390/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11391/// elements from either LHS or RHS, return the shuffle mask and true.
11392/// Otherwise, return false.
11393static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11394 std::vector<Constant*> &Mask) {
11395 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11396 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011397 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011398
11399 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011400 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011401 return true;
11402 } else if (V == LHS) {
11403 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011404 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011405 return true;
11406 } else if (V == RHS) {
11407 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011408 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011409 return true;
11410 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11411 // If this is an insert of an extract from some other vector, include it.
11412 Value *VecOp = IEI->getOperand(0);
11413 Value *ScalarOp = IEI->getOperand(1);
11414 Value *IdxOp = IEI->getOperand(2);
11415
Chris Lattnerd929f062006-04-27 21:14:21 +000011416 if (!isa<ConstantInt>(IdxOp))
11417 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011418 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011419
11420 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11421 // Okay, we can handle this if the vector we are insertinting into is
11422 // transitively ok.
11423 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11424 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011425 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011426 return true;
11427 }
11428 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11429 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011430 EI->getOperand(0)->getType() == V->getType()) {
11431 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011432 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011433
11434 // This must be extracting from either LHS or RHS.
11435 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11436 // Okay, we can handle this if the vector we are insertinting into is
11437 // transitively ok.
11438 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11439 // If so, update the mask to reflect the inserted value.
11440 if (EI->getOperand(0) == LHS) {
11441 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011442 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011443 } else {
11444 assert(EI->getOperand(0) == RHS);
11445 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011446 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011447
11448 }
11449 return true;
11450 }
11451 }
11452 }
11453 }
11454 }
11455 // TODO: Handle shufflevector here!
11456
11457 return false;
11458}
11459
11460/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11461/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11462/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011463static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011464 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011465 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011466 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011467 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011468 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011469
11470 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011471 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011472 return V;
11473 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011474 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011475 return V;
11476 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11477 // If this is an insert of an extract from some other vector, include it.
11478 Value *VecOp = IEI->getOperand(0);
11479 Value *ScalarOp = IEI->getOperand(1);
11480 Value *IdxOp = IEI->getOperand(2);
11481
11482 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11483 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11484 EI->getOperand(0)->getType() == V->getType()) {
11485 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011486 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11487 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011488
11489 // Either the extracted from or inserted into vector must be RHSVec,
11490 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011491 if (EI->getOperand(0) == RHS || RHS == 0) {
11492 RHS = EI->getOperand(0);
11493 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011494 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011495 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011496 return V;
11497 }
11498
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011499 if (VecOp == RHS) {
11500 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011501 // Everything but the extracted element is replaced with the RHS.
11502 for (unsigned i = 0; i != NumElts; ++i) {
11503 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011504 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011505 }
11506 return V;
11507 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011508
11509 // If this insertelement is a chain that comes from exactly these two
11510 // vectors, return the vector and the effective shuffle.
11511 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11512 return EI->getOperand(0);
11513
Chris Lattnerefb47352006-04-15 01:39:45 +000011514 }
11515 }
11516 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011517 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011518
11519 // Otherwise, can't do anything fancy. Return an identity vector.
11520 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011521 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011522 return V;
11523}
11524
11525Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11526 Value *VecOp = IE.getOperand(0);
11527 Value *ScalarOp = IE.getOperand(1);
11528 Value *IdxOp = IE.getOperand(2);
11529
Chris Lattner599ded12007-04-09 01:11:16 +000011530 // Inserting an undef or into an undefined place, remove this.
11531 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11532 ReplaceInstUsesWith(IE, VecOp);
11533
Chris Lattnerefb47352006-04-15 01:39:45 +000011534 // If the inserted element was extracted from some other vector, and if the
11535 // indexes are constant, try to turn this into a shufflevector operation.
11536 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11537 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11538 EI->getOperand(0)->getType() == IE.getType()) {
11539 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011540 unsigned ExtractedIdx =
11541 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011542 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011543
11544 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11545 return ReplaceInstUsesWith(IE, VecOp);
11546
11547 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11548 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11549
11550 // If we are extracting a value from a vector, then inserting it right
11551 // back into the same place, just use the input vector.
11552 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11553 return ReplaceInstUsesWith(IE, VecOp);
11554
11555 // We could theoretically do this for ANY input. However, doing so could
11556 // turn chains of insertelement instructions into a chain of shufflevector
11557 // instructions, and right now we do not merge shufflevectors. As such,
11558 // only do this in a situation where it is clear that there is benefit.
11559 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11560 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11561 // the values of VecOp, except then one read from EIOp0.
11562 // Build a new shuffle mask.
11563 std::vector<Constant*> Mask;
11564 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011565 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011566 else {
11567 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011568 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011569 NumVectorElts));
11570 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011571 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011572 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011573 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011574 }
11575
11576 // If this insertelement isn't used by some other insertelement, turn it
11577 // (and any insertelements it points to), into one big shuffle.
11578 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11579 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011580 Value *RHS = 0;
11581 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11582 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11583 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011584 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011585 }
11586 }
11587 }
11588
11589 return 0;
11590}
11591
11592
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011593Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11594 Value *LHS = SVI.getOperand(0);
11595 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011596 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011597
11598 bool MadeChange = false;
11599
Chris Lattner867b99f2006-10-05 06:55:50 +000011600 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011601 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011602 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11603
Chris Lattnere4929dd2007-01-05 07:36:08 +000011604 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011605 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011606 if (isa<UndefValue>(SVI.getOperand(1))) {
11607 // Scan to see if there are any references to the RHS. If so, replace them
11608 // with undef element refs and set MadeChange to true.
11609 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11610 if (Mask[i] >= e && Mask[i] != 2*e) {
11611 Mask[i] = 2*e;
11612 MadeChange = true;
11613 }
11614 }
11615
11616 if (MadeChange) {
11617 // Remap any references to RHS to use LHS.
11618 std::vector<Constant*> Elts;
11619 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11620 if (Mask[i] == 2*e)
11621 Elts.push_back(UndefValue::get(Type::Int32Ty));
11622 else
11623 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11624 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011625 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011626 }
11627 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011628
Chris Lattner863bcff2006-05-25 23:48:38 +000011629 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11630 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11631 if (LHS == RHS || isa<UndefValue>(LHS)) {
11632 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011633 // shuffle(undef,undef,mask) -> undef.
11634 return ReplaceInstUsesWith(SVI, LHS);
11635 }
11636
Chris Lattner863bcff2006-05-25 23:48:38 +000011637 // Remap any references to RHS to use LHS.
11638 std::vector<Constant*> Elts;
11639 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011640 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011641 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011642 else {
11643 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11644 (Mask[i] < e && isa<UndefValue>(LHS)))
11645 Mask[i] = 2*e; // Turn into undef.
11646 else
11647 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011648 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011649 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011650 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011651 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011652 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011653 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011654 LHS = SVI.getOperand(0);
11655 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011656 MadeChange = true;
11657 }
11658
Chris Lattner7b2e27922006-05-26 00:29:06 +000011659 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011660 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011661
Chris Lattner863bcff2006-05-25 23:48:38 +000011662 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11663 if (Mask[i] >= e*2) continue; // Ignore undef values.
11664 // Is this an identity shuffle of the LHS value?
11665 isLHSID &= (Mask[i] == i);
11666
11667 // Is this an identity shuffle of the RHS value?
11668 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011669 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011670
Chris Lattner863bcff2006-05-25 23:48:38 +000011671 // Eliminate identity shuffles.
11672 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11673 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011674
Chris Lattner7b2e27922006-05-26 00:29:06 +000011675 // If the LHS is a shufflevector itself, see if we can combine it with this
11676 // one without producing an unusual shuffle. Here we are really conservative:
11677 // we are absolutely afraid of producing a shuffle mask not in the input
11678 // program, because the code gen may not be smart enough to turn a merged
11679 // shuffle into two specific shuffles: it may produce worse code. As such,
11680 // we only merge two shuffles if the result is one of the two input shuffle
11681 // masks. In this case, merging the shuffles just removes one instruction,
11682 // which we know is safe. This is good for things like turning:
11683 // (splat(splat)) -> splat.
11684 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11685 if (isa<UndefValue>(RHS)) {
11686 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11687
11688 std::vector<unsigned> NewMask;
11689 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11690 if (Mask[i] >= 2*e)
11691 NewMask.push_back(2*e);
11692 else
11693 NewMask.push_back(LHSMask[Mask[i]]);
11694
11695 // If the result mask is equal to the src shuffle or this shuffle mask, do
11696 // the replacement.
11697 if (NewMask == LHSMask || NewMask == Mask) {
11698 std::vector<Constant*> Elts;
11699 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11700 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011701 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011702 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011703 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011704 }
11705 }
11706 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11707 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011708 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011709 }
11710 }
11711 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011712
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011713 return MadeChange ? &SVI : 0;
11714}
11715
11716
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011717
Chris Lattnerea1c4542004-12-08 23:43:58 +000011718
11719/// TryToSinkInstruction - Try to move the specified instruction from its
11720/// current block into the beginning of DestBlock, which can only happen if it's
11721/// safe to move the instruction past all of the instructions between it and the
11722/// end of its block.
11723static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11724 assert(I->hasOneUse() && "Invariants didn't hold!");
11725
Chris Lattner108e9022005-10-27 17:13:11 +000011726 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011727 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11728 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011729
Chris Lattnerea1c4542004-12-08 23:43:58 +000011730 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011731 if (isa<AllocaInst>(I) && I->getParent() ==
11732 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011733 return false;
11734
Chris Lattner96a52a62004-12-09 07:14:34 +000011735 // We can only sink load instructions if there is nothing between the load and
11736 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011737 if (I->mayReadFromMemory()) {
11738 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011739 Scan != E; ++Scan)
11740 if (Scan->mayWriteToMemory())
11741 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011742 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011743
Dan Gohman02dea8b2008-05-23 21:05:58 +000011744 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011745
Chris Lattner4bc5f802005-08-08 19:11:57 +000011746 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011747 ++NumSunkInst;
11748 return true;
11749}
11750
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011751
11752/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11753/// all reachable code to the worklist.
11754///
11755/// This has a couple of tricks to make the code faster and more powerful. In
11756/// particular, we constant fold and DCE instructions as we go, to avoid adding
11757/// them to the worklist (this significantly speeds up instcombine on code where
11758/// many instructions are dead or constant). Additionally, if we find a branch
11759/// whose condition is a known constant, we only visit the reachable successors.
11760///
11761static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011762 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011763 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011764 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011765 std::vector<BasicBlock*> Worklist;
11766 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011767
Chris Lattner2c7718a2007-03-23 19:17:18 +000011768 while (!Worklist.empty()) {
11769 BB = Worklist.back();
11770 Worklist.pop_back();
11771
11772 // We have now visited this block! If we've already been here, ignore it.
11773 if (!Visited.insert(BB)) continue;
11774
11775 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11776 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011777
Chris Lattner2c7718a2007-03-23 19:17:18 +000011778 // DCE instruction if trivially dead.
11779 if (isInstructionTriviallyDead(Inst)) {
11780 ++NumDeadInst;
11781 DOUT << "IC: DCE: " << *Inst;
11782 Inst->eraseFromParent();
11783 continue;
11784 }
11785
11786 // ConstantProp instruction if trivially constant.
11787 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11788 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11789 Inst->replaceAllUsesWith(C);
11790 ++NumConstProp;
11791 Inst->eraseFromParent();
11792 continue;
11793 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011794
Chris Lattner2c7718a2007-03-23 19:17:18 +000011795 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011796 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011797
11798 // Recursively visit successors. If this is a branch or switch on a
11799 // constant, only visit the reachable successor.
11800 TerminatorInst *TI = BB->getTerminator();
11801 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11802 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11803 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011804 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011805 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011806 continue;
11807 }
11808 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11809 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11810 // See if this is an explicit destination.
11811 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11812 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011813 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011814 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011815 continue;
11816 }
11817
11818 // Otherwise it is the default destination.
11819 Worklist.push_back(SI->getSuccessor(0));
11820 continue;
11821 }
11822 }
11823
11824 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11825 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011826 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011827}
11828
Chris Lattnerec9c3582007-03-03 02:04:50 +000011829bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011830 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011831 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011832
11833 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11834 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011835
Chris Lattnerb3d59702005-07-07 20:40:38 +000011836 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011837 // Do a depth-first traversal of the function, populate the worklist with
11838 // the reachable instructions. Ignore blocks that are not reachable. Keep
11839 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011840 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011841 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011842
Chris Lattnerb3d59702005-07-07 20:40:38 +000011843 // Do a quick scan over the function. If we find any blocks that are
11844 // unreachable, remove any instructions inside of them. This prevents
11845 // the instcombine code from having to deal with some bad special cases.
11846 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11847 if (!Visited.count(BB)) {
11848 Instruction *Term = BB->getTerminator();
11849 while (Term != BB->begin()) { // Remove instrs bottom-up
11850 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011851
Bill Wendlingb7427032006-11-26 09:46:52 +000011852 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011853 ++NumDeadInst;
11854
11855 if (!I->use_empty())
11856 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11857 I->eraseFromParent();
11858 }
11859 }
11860 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011861
Chris Lattnerdbab3862007-03-02 21:28:56 +000011862 while (!Worklist.empty()) {
11863 Instruction *I = RemoveOneFromWorkList();
11864 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011865
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011866 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011867 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011868 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011869 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011870 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011871 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011872
Bill Wendlingb7427032006-11-26 09:46:52 +000011873 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011874
11875 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011876 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011877 continue;
11878 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011879
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011880 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011881 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011882 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011883
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011884 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011885 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011886 ReplaceInstUsesWith(*I, C);
11887
Chris Lattner62b14df2002-09-02 04:59:56 +000011888 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011889 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011890 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011891 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011892 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011893
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000011894 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11895 // See if we can constant fold its operands.
11896 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11897 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11898 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11899 i->set(NewC);
11900 }
11901 }
11902 }
11903
Chris Lattnerea1c4542004-12-08 23:43:58 +000011904 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011905 // FIXME: Remove GetResultInst test when first class support for aggregates
11906 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011907 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011908 BasicBlock *BB = I->getParent();
11909 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11910 if (UserParent != BB) {
11911 bool UserIsSuccessor = false;
11912 // See if the user is one of our successors.
11913 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11914 if (*SI == UserParent) {
11915 UserIsSuccessor = true;
11916 break;
11917 }
11918
11919 // If the user is one of our immediate successors, and if that successor
11920 // only has us as a predecessors (we'd have to split the critical edge
11921 // otherwise), we can keep going.
11922 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11923 next(pred_begin(UserParent)) == pred_end(UserParent))
11924 // Okay, the CFG is simple enough, try to sink this instruction.
11925 Changed |= TryToSinkInstruction(I, UserParent);
11926 }
11927 }
11928
Chris Lattner8a2a3112001-12-14 16:52:21 +000011929 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011930#ifndef NDEBUG
11931 std::string OrigI;
11932#endif
11933 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011934 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011935 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011936 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011937 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011938 DOUT << "IC: Old = " << *I
11939 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011940
Chris Lattnerf523d062004-06-09 05:08:07 +000011941 // Everything uses the new instruction now.
11942 I->replaceAllUsesWith(Result);
11943
11944 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011945 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011946 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011947
Chris Lattner6934a042007-02-11 01:23:03 +000011948 // Move the name to the new instruction first.
11949 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011950
11951 // Insert the new instruction into the basic block...
11952 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011953 BasicBlock::iterator InsertPos = I;
11954
11955 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11956 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11957 ++InsertPos;
11958
11959 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011960
Chris Lattner00d51312004-05-01 23:27:23 +000011961 // Make sure that we reprocess all operands now that we reduced their
11962 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011963 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011964
Chris Lattnerf523d062004-06-09 05:08:07 +000011965 // Instructions can end up on the worklist more than once. Make sure
11966 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011967 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011968
11969 // Erase the old instruction.
11970 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011971 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011972#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011973 DOUT << "IC: Mod = " << OrigI
11974 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011975#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011976
Chris Lattner90ac28c2002-08-02 19:29:35 +000011977 // If the instruction was modified, it's possible that it is now dead.
11978 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011979 if (isInstructionTriviallyDead(I)) {
11980 // Make sure we process all operands now that we are reducing their
11981 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011982 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011983
Chris Lattner00d51312004-05-01 23:27:23 +000011984 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011985 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011986 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011987 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011988 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011989 AddToWorkList(I);
11990 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011991 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011992 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011993 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011994 }
11995 }
11996
Chris Lattnerec9c3582007-03-03 02:04:50 +000011997 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011998
11999 // Do an explicit clear, this shrinks the map if needed.
12000 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012001 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012002}
12003
Chris Lattnerec9c3582007-03-03 02:04:50 +000012004
12005bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012006 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12007
Chris Lattnerec9c3582007-03-03 02:04:50 +000012008 bool EverMadeChange = false;
12009
12010 // Iterate while there is work to do.
12011 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012012 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012013 EverMadeChange = true;
12014 return EverMadeChange;
12015}
12016
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012017FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012018 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012019}
Brian Gaeked0fde302003-11-11 22:41:34 +000012020