blob: 62185c63d9b6e3a9afc2871a286b42d801372f82 [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);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000188 Instruction *visitFCmpInst(FCmpInst &I);
189 Instruction *visitICmpInst(ICmpInst &I);
190 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000191 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
192 Instruction *LHS,
193 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000194 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
195 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000196
Reid Spencere4d87aa2006-12-23 06:05:41 +0000197 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
198 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000199 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000200 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000201 Instruction *commonCastTransforms(CastInst &CI);
202 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000203 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000204 Instruction *visitTrunc(TruncInst &CI);
205 Instruction *visitZExt(ZExtInst &CI);
206 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000207 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000208 Instruction *visitFPExt(CastInst &CI);
209 Instruction *visitFPToUI(CastInst &CI);
210 Instruction *visitFPToSI(CastInst &CI);
211 Instruction *visitUIToFP(CastInst &CI);
212 Instruction *visitSIToFP(CastInst &CI);
213 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000214 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000215 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000216 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
217 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000218 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000219 Instruction *visitCallInst(CallInst &CI);
220 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000221 Instruction *visitPHINode(PHINode &PN);
222 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000223 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000224 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000225 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000226 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000227 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000228 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000229 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000230 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000231 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000232
233 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000234 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000235
Chris Lattner9fe38862003-06-19 17:00:31 +0000236 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000237 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000238 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000239 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000240 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
241 bool DoXform = true);
Chris Lattner9fe38862003-06-19 17:00:31 +0000242
Chris Lattner28977af2004-04-05 01:30:19 +0000243 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000244 // InsertNewInstBefore - insert an instruction New before instruction Old
245 // in the program. Add the new instruction to the worklist.
246 //
Chris Lattner955f3312004-09-28 21:48:02 +0000247 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000248 assert(New && New->getParent() == 0 &&
249 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000250 BasicBlock *BB = Old.getParent();
251 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000252 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000253 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000254 }
255
Chris Lattner0c967662004-09-24 15:21:34 +0000256 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
257 /// This also adds the cast to the worklist. Finally, this returns the
258 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000259 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
260 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000261 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000262
Chris Lattnere2ed0572006-04-06 19:19:17 +0000263 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000264 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000265
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000266 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000267 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000268 return C;
269 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000270
271 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
272 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
273 }
274
Chris Lattner0c967662004-09-24 15:21:34 +0000275
Chris Lattner8b170942002-08-09 23:47:40 +0000276 // ReplaceInstUsesWith - This method is to be used when an instruction is
277 // found to be dead, replacable with another preexisting expression. Here
278 // we add all uses of I to the worklist, replace all uses of I with the new
279 // value, then return I, so that the inst combiner will know that I was
280 // modified.
281 //
282 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000283 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000284 if (&I != V) {
285 I.replaceAllUsesWith(V);
286 return &I;
287 } else {
288 // If we are replacing the instruction with itself, this must be in a
289 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000290 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000291 return &I;
292 }
Chris Lattner8b170942002-08-09 23:47:40 +0000293 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000294
Chris Lattner6dce1a72006-02-07 06:56:34 +0000295 // UpdateValueUsesWith - This method is to be used when an value is
296 // found to be replacable with another preexisting expression or was
297 // updated. Here we add all uses of I to the worklist, replace all uses of
298 // I with the new value (unless the instruction was just updated), then
299 // return true, so that the inst combiner will know that I was modified.
300 //
301 bool UpdateValueUsesWith(Value *Old, Value *New) {
302 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
303 if (Old != New)
304 Old->replaceAllUsesWith(New);
305 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000306 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000307 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000308 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000309 return true;
310 }
311
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000312 // EraseInstFromFunction - When dealing with an instruction that has side
313 // effects or produces a void value, we can't rely on DCE to delete the
314 // instruction. Instead, visit methods should return the value returned by
315 // this function.
316 Instruction *EraseInstFromFunction(Instruction &I) {
317 assert(I.use_empty() && "Cannot erase instruction that is used!");
318 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000319 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000320 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000321 return 0; // Don't do anything with FI
322 }
323
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000324 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000325 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
326 /// InsertBefore instruction. This is specialized a bit to avoid inserting
327 /// casts that are known to not do anything...
328 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000329 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
330 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000331 Instruction *InsertBefore);
332
Reid Spencere4d87aa2006-12-23 06:05:41 +0000333 /// SimplifyCommutative - This performs a few simplifications for
334 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000335 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000336
Reid Spencere4d87aa2006-12-23 06:05:41 +0000337 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338 /// most-complex to least-complex order.
339 bool SimplifyCompare(CmpInst &I);
340
Reid Spencer2ec619a2007-03-23 21:24:59 +0000341 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
342 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000343 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
344 APInt& KnownZero, APInt& KnownOne,
345 unsigned Depth = 0);
346
Chris Lattner867b99f2006-10-05 06:55:50 +0000347 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
348 uint64_t &UndefElts, unsigned Depth = 0);
349
Chris Lattner4e998b22004-09-29 05:07:12 +0000350 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
351 // PHI node as operand #0, see if we can fold the instruction into the PHI
352 // (which is only possible if all operands to the PHI are constants).
353 Instruction *FoldOpIntoPhi(Instruction &I);
354
Chris Lattnerbac32862004-11-14 19:13:23 +0000355 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
356 // operator and they all are only used by the PHI, PHI together their
357 // inputs, and do the operation once, to the result of the PHI.
358 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000359 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
360
361
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000362 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
363 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000364
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000365 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000366 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000367 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000368 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000369 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000370 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000371 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000372 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000373 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000374
Chris Lattnerafe91a52006-06-15 19:07:26 +0000375
Reid Spencerc55b2432006-12-13 18:21:21 +0000376 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000377
378 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
379 APInt& KnownOne, unsigned Depth = 0);
380 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
381 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
382 unsigned CastOpc,
383 int &NumCastsRemoved);
384 unsigned GetOrEnforceKnownAlignment(Value *V,
385 unsigned PrefAlign = 0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000386 };
387}
388
Dan Gohman844731a2008-05-13 00:00:25 +0000389char InstCombiner::ID = 0;
390static RegisterPass<InstCombiner>
391X("instcombine", "Combine redundant instructions");
392
Chris Lattner4f98c562003-03-10 21:43:22 +0000393// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000394// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000395static unsigned getComplexity(Value *V) {
396 if (isa<Instruction>(V)) {
397 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000398 return 3;
399 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000400 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000401 if (isa<Argument>(V)) return 3;
402 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000403}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000404
Chris Lattnerc8802d22003-03-11 00:12:48 +0000405// isOnlyUse - Return true if this instruction will be deleted if we stop using
406// it.
407static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000408 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000409}
410
Chris Lattner4cb170c2004-02-23 06:38:22 +0000411// getPromotedType - Return the specified type promoted as it would be to pass
412// though a va_arg area...
413static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000414 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
415 if (ITy->getBitWidth() < 32)
416 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000417 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000418 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000419}
420
Reid Spencer3da59db2006-11-27 01:05:10 +0000421/// getBitCastOperand - If the specified operand is a CastInst or a constant
422/// expression bitcast, return the operand value, otherwise return null.
423static Value *getBitCastOperand(Value *V) {
424 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000425 return I->getOperand(0);
426 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000427 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000428 return CE->getOperand(0);
429 return 0;
430}
431
Reid Spencer3da59db2006-11-27 01:05:10 +0000432/// This function is a wrapper around CastInst::isEliminableCastPair. It
433/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000434static Instruction::CastOps
435isEliminableCastPair(
436 const CastInst *CI, ///< The first cast instruction
437 unsigned opcode, ///< The opcode of the second cast instruction
438 const Type *DstTy, ///< The target type for the second cast instruction
439 TargetData *TD ///< The target data for pointer size
440) {
441
442 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
443 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000444
Reid Spencer3da59db2006-11-27 01:05:10 +0000445 // Get the opcodes of the two Cast instructions
446 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
447 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000448
Reid Spencer3da59db2006-11-27 01:05:10 +0000449 return Instruction::CastOps(
450 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
451 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000452}
453
454/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
455/// in any code being generated. It does not require codegen if V is simple
456/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000457static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
458 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000459 if (V->getType() == Ty || isa<Constant>(V)) return false;
460
Chris Lattner01575b72006-05-25 23:24:33 +0000461 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000462 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000463 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000464 return false;
465 return true;
466}
467
468/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
469/// InsertBefore instruction. This is specialized a bit to avoid inserting
470/// casts that are known to not do anything...
471///
Reid Spencer17212df2006-12-12 09:18:51 +0000472Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
473 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000474 Instruction *InsertBefore) {
475 if (V->getType() == DestTy) return V;
476 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000477 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000478
Reid Spencer17212df2006-12-12 09:18:51 +0000479 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000480}
481
Chris Lattner4f98c562003-03-10 21:43:22 +0000482// SimplifyCommutative - This performs a few simplifications for commutative
483// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000484//
Chris Lattner4f98c562003-03-10 21:43:22 +0000485// 1. Order operands such that they are listed from right (least complex) to
486// left (most complex). This puts constants before unary operators before
487// binary operators.
488//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000489// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
490// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000491//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000492bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000493 bool Changed = false;
494 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
495 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000496
Chris Lattner4f98c562003-03-10 21:43:22 +0000497 if (!I.isAssociative()) return Changed;
498 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000499 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
500 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
501 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000502 Constant *Folded = ConstantExpr::get(I.getOpcode(),
503 cast<Constant>(I.getOperand(1)),
504 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000505 I.setOperand(0, Op->getOperand(0));
506 I.setOperand(1, Folded);
507 return true;
508 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
509 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
510 isOnlyUse(Op) && isOnlyUse(Op1)) {
511 Constant *C1 = cast<Constant>(Op->getOperand(1));
512 Constant *C2 = cast<Constant>(Op1->getOperand(1));
513
514 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000515 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000516 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000517 Op1->getOperand(0),
518 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000519 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000520 I.setOperand(0, New);
521 I.setOperand(1, Folded);
522 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000523 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000524 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000525 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000526}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000527
Reid Spencere4d87aa2006-12-23 06:05:41 +0000528/// SimplifyCompare - For a CmpInst this function just orders the operands
529/// so that theyare listed from right (least complex) to left (most complex).
530/// This puts constants before unary operators before binary operators.
531bool InstCombiner::SimplifyCompare(CmpInst &I) {
532 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
533 return false;
534 I.swapOperands();
535 // Compare instructions are not associative so there's nothing else we can do.
536 return true;
537}
538
Chris Lattner8d969642003-03-10 23:06:50 +0000539// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
540// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000541//
Chris Lattner8d969642003-03-10 23:06:50 +0000542static inline Value *dyn_castNegVal(Value *V) {
543 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000544 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000545
Chris Lattner0ce85802004-12-14 20:08:06 +0000546 // Constants can be considered to be negated values if they can be folded.
547 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
548 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000549 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000550}
551
Chris Lattner8d969642003-03-10 23:06:50 +0000552static inline Value *dyn_castNotVal(Value *V) {
553 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000554 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000555
556 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000557 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000558 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000559 return 0;
560}
561
Chris Lattnerc8802d22003-03-11 00:12:48 +0000562// dyn_castFoldableMul - If this value is a multiply that can be folded into
563// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000564// non-constant operand of the multiply, and set CST to point to the multiplier.
565// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000566//
Chris Lattner50af16a2004-11-13 19:50:12 +0000567static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000568 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000569 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000570 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000571 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000572 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000573 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000574 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000575 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000576 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000577 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000578 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000579 return I->getOperand(0);
580 }
581 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000582 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000583}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000584
Chris Lattner574da9b2005-01-13 20:14:25 +0000585/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
586/// expression, return it.
587static User *dyn_castGetElementPtr(Value *V) {
588 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
589 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
590 if (CE->getOpcode() == Instruction::GetElementPtr)
591 return cast<User>(V);
592 return false;
593}
594
Dan Gohmaneee962e2008-04-10 18:43:06 +0000595/// getOpcode - If this is an Instruction or a ConstantExpr, return the
596/// opcode value. Otherwise return UserOp1.
597static unsigned getOpcode(User *U) {
598 if (Instruction *I = dyn_cast<Instruction>(U))
599 return I->getOpcode();
600 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
601 return CE->getOpcode();
602 // Use UserOp1 to mean there's no opcode.
603 return Instruction::UserOp1;
604}
605
Reid Spencer7177c3a2007-03-25 05:33:51 +0000606/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000607static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000608 APInt Val(C->getValue());
609 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000610}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000611/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000612static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000613 APInt Val(C->getValue());
614 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000615}
616/// Add - Add two ConstantInts together
617static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
618 return ConstantInt::get(C1->getValue() + C2->getValue());
619}
620/// And - Bitwise AND two ConstantInts together
621static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
622 return ConstantInt::get(C1->getValue() & C2->getValue());
623}
624/// Subtract - Subtract one ConstantInt from another
625static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
626 return ConstantInt::get(C1->getValue() - C2->getValue());
627}
628/// Multiply - Multiply two ConstantInts together
629static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
630 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000631}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000632/// MultiplyOverflows - True if the multiply can not be expressed in an int
633/// this size.
634static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
635 uint32_t W = C1->getBitWidth();
636 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
637 if (sign) {
638 LHSExt.sext(W * 2);
639 RHSExt.sext(W * 2);
640 } else {
641 LHSExt.zext(W * 2);
642 RHSExt.zext(W * 2);
643 }
644
645 APInt MulExt = LHSExt * RHSExt;
646
647 if (sign) {
648 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
649 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
650 return MulExt.slt(Min) || MulExt.sgt(Max);
651 } else
652 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
653}
Chris Lattner955f3312004-09-28 21:48:02 +0000654
Chris Lattner68d5ff22006-02-09 07:38:58 +0000655/// ComputeMaskedBits - Determine which of the bits specified in Mask are
656/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000657/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
658/// processing.
659/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
660/// we cannot optimize based on the assumption that it is zero without changing
661/// it to be an explicit zero. If we don't change it to zero, other code could
662/// optimized based on the contradictory assumption that it is non-zero.
663/// Because instcombine aggressively folds operations with undef args anyway,
664/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000665void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
666 APInt& KnownZero, APInt& KnownOne,
667 unsigned Depth) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000668 assert(V && "No Value?");
669 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000670 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000671 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
672 "Not integer or pointer type!");
673 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
674 (!isa<IntegerType>(V->getType()) ||
675 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000676 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000677 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000678 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000679 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
680 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000681 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000682 KnownZero = ~KnownOne & Mask;
683 return;
684 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000685 // Null is all-zeros.
686 if (isa<ConstantPointerNull>(V)) {
687 KnownOne.clear();
688 KnownZero = Mask;
689 return;
690 }
691 // The address of an aligned GlobalValue has trailing zeros.
692 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
693 unsigned Align = GV->getAlignment();
694 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
695 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
696 if (Align > 0)
697 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
698 CountTrailingZeros_32(Align));
699 else
700 KnownZero.clear();
701 KnownOne.clear();
702 return;
703 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000704
Dan Gohman23e8b712008-04-28 17:02:21 +0000705 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
706
Reid Spencer3e7594f2007-03-08 01:46:38 +0000707 if (Depth == 6 || Mask == 0)
708 return; // Limit search depth.
709
Dan Gohmaneee962e2008-04-10 18:43:06 +0000710 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000711 if (!I) return;
712
713 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000714 switch (getOpcode(I)) {
715 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000716 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000717 // If either the LHS or the RHS are Zero, the result is zero.
718 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000719 APInt Mask2(Mask & ~KnownZero);
720 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000721 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
722 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
723
724 // Output known-1 bits are only known if set in both the LHS & RHS.
725 KnownOne &= KnownOne2;
726 // Output known-0 are known to be clear if zero in either the LHS | RHS.
727 KnownZero |= KnownZero2;
728 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000729 }
730 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000731 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000732 APInt Mask2(Mask & ~KnownOne);
733 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000734 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
735 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
736
737 // Output known-0 bits are only known if clear in both the LHS & RHS.
738 KnownZero &= KnownZero2;
739 // Output known-1 are known to be set if set in either the LHS | RHS.
740 KnownOne |= KnownOne2;
741 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000742 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000743 case Instruction::Xor: {
744 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
745 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
746 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
747 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
748
749 // Output known-0 bits are known if clear or set in both the LHS & RHS.
750 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
751 // Output known-1 are known to be set if set in only one of the LHS, RHS.
752 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
753 KnownZero = KnownZeroOut;
754 return;
755 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000756 case Instruction::Mul: {
757 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
758 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
759 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
760 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
761 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
762
763 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman23e8b712008-04-28 17:02:21 +0000764 // Also compute a conserative estimate for high known-0 bits.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000765 // More trickiness is possible, but this is sufficient for the
766 // interesting case of alignment computation.
767 KnownOne.clear();
768 unsigned TrailZ = KnownZero.countTrailingOnes() +
769 KnownZero2.countTrailingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +0000770 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman42ac9292008-05-07 00:35:55 +0000771 KnownZero2.countLeadingOnes(),
772 BitWidth) - BitWidth;
Dan Gohman23e8b712008-04-28 17:02:21 +0000773
Dan Gohmaneee962e2008-04-10 18:43:06 +0000774 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000775 LeadZ = std::min(LeadZ, BitWidth);
776 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
777 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000778 KnownZero &= Mask;
779 return;
780 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000781 case Instruction::UDiv: {
782 // For the purposes of computing leading zeros we can conservatively
783 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1d9cd502008-05-02 21:30:02 +0000784 // be less than the denominator.
Dan Gohman23e8b712008-04-28 17:02:21 +0000785 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
786 ComputeMaskedBits(I->getOperand(0),
787 AllOnes, KnownZero2, KnownOne2, Depth+1);
788 unsigned LeadZ = KnownZero2.countLeadingOnes();
789
790 KnownOne2.clear();
791 KnownZero2.clear();
792 ComputeMaskedBits(I->getOperand(1),
793 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1d9cd502008-05-02 21:30:02 +0000794 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
795 if (RHSUnknownLeadingOnes != BitWidth)
796 LeadZ = std::min(BitWidth,
797 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000798
799 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
800 return;
801 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000802 case Instruction::Select:
803 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
804 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
805 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
806 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
807
808 // Only known if known in both the LHS and RHS.
809 KnownOne &= KnownOne2;
810 KnownZero &= KnownZero2;
811 return;
812 case Instruction::FPTrunc:
813 case Instruction::FPExt:
814 case Instruction::FPToUI:
815 case Instruction::FPToSI:
816 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000817 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000818 return; // Can't work with floating point.
819 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000820 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000821 // We can't handle these if we don't know the pointer size.
822 if (!TD) return;
823 // Fall through and handle them the same as zext/trunc.
824 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000825 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000826 // All these have integer operands
Dan Gohmaneee962e2008-04-10 18:43:06 +0000827 const Type *SrcTy = I->getOperand(0)->getType();
828 uint32_t SrcBitWidth = TD ?
829 TD->getTypeSizeInBits(SrcTy) :
830 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000831 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000832 MaskIn.zextOrTrunc(SrcBitWidth);
833 KnownZero.zextOrTrunc(SrcBitWidth);
834 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000835 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000836 KnownZero.zextOrTrunc(BitWidth);
837 KnownOne.zextOrTrunc(BitWidth);
838 // Any top bits are known to be zero.
839 if (BitWidth > SrcBitWidth)
840 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000841 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000842 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000843 case Instruction::BitCast: {
844 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000845 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000846 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
847 return;
848 }
849 break;
850 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000851 case Instruction::SExt: {
852 // Compute the bits in the result that are not present in the input.
853 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000854 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000855
Zhou Shengaa305ab2007-03-28 02:19:03 +0000856 APInt MaskIn(Mask);
857 MaskIn.trunc(SrcBitWidth);
858 KnownZero.trunc(SrcBitWidth);
859 KnownOne.trunc(SrcBitWidth);
860 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000861 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000862 KnownZero.zext(BitWidth);
863 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000864
865 // If the sign bit of the input is known set or clear, then we know the
866 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000867 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000868 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000869 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000870 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000871 return;
872 }
873 case Instruction::Shl:
874 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
875 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000876 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000877 APInt Mask2(Mask.lshr(ShiftAmt));
878 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000879 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000880 KnownZero <<= ShiftAmt;
881 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000882 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000883 return;
884 }
885 break;
886 case Instruction::LShr:
887 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
888 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
889 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000890 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000891
892 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000893 APInt Mask2(Mask.shl(ShiftAmt));
894 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000895 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
896 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
897 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000898 // high bits known zero.
899 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000900 return;
901 }
902 break;
903 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000904 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000905 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
906 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000907 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000908
909 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000910 APInt Mask2(Mask.shl(ShiftAmt));
911 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000912 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
913 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
914 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
915
Zhou Shengaa305ab2007-03-28 02:19:03 +0000916 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
917 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000918 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000919 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000920 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000921 return;
922 }
923 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000924 case Instruction::Sub: {
925 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
926 // We know that the top bits of C-X are clear if X contains less bits
927 // than C (i.e. no wrap-around can happen). For example, 20-X is
928 // positive if we can prove that X is >= 0 and < 16.
929 if (!CLHS->getValue().isNegative()) {
930 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
931 // NLZ can't be BitWidth with no sign bit
932 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000933 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
934 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000935
Dan Gohman23e8b712008-04-28 17:02:21 +0000936 // If all of the MaskV bits are known to be zero, then we know the
937 // output top bits are zero, because we now know that the output is
938 // from [0-C].
939 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000940 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
941 // Top bits known zero.
942 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000943 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000944 }
945 }
946 }
947 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000948 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000949 // Output known-0 bits are known if clear or set in both the low clear bits
950 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
951 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000952 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
953 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
954 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
955 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
956
957 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
958 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
959 KnownZeroOut = std::min(KnownZeroOut,
960 KnownZero2.countTrailingOnes());
961
962 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000963 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000964 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000965 case Instruction::SRem:
966 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
967 APInt RA = Rem->getValue();
968 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000969 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000970 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
971 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
972
973 // The sign of a remainder is equal to the sign of the first
974 // operand (zero being positive).
975 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
976 KnownZero2 |= ~LowBits;
977 else if (KnownOne2[BitWidth-1])
978 KnownOne2 |= ~LowBits;
979
980 KnownZero |= KnownZero2 & Mask;
981 KnownOne |= KnownOne2 & Mask;
982
983 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
984 }
985 }
986 break;
Dan Gohman23e8b712008-04-28 17:02:21 +0000987 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000988 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
989 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +0000990 if (RA.isPowerOf2()) {
991 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000992 APInt Mask2 = LowBits & Mask;
993 KnownZero |= ~LowBits & Mask;
994 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
995 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +0000996 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000997 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000998 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000999
1000 // Since the result is less than or equal to either operand, any leading
1001 // zero bits in either operand must also exist in the result.
1002 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1003 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1004 Depth+1);
1005 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1006 Depth+1);
1007
1008 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1009 KnownZero2.countLeadingOnes());
1010 KnownOne.clear();
1011 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001012 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001013 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001014
1015 case Instruction::Alloca:
1016 case Instruction::Malloc: {
1017 AllocationInst *AI = cast<AllocationInst>(V);
1018 unsigned Align = AI->getAlignment();
1019 if (Align == 0 && TD) {
1020 if (isa<AllocaInst>(AI))
1021 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1022 else if (isa<MallocInst>(AI)) {
1023 // Malloc returns maximally aligned memory.
1024 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1025 Align =
1026 std::max(Align,
1027 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1028 Align =
1029 std::max(Align,
1030 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1031 }
1032 }
1033
1034 if (Align > 0)
1035 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1036 CountTrailingZeros_32(Align));
1037 break;
1038 }
1039 case Instruction::GetElementPtr: {
1040 // Analyze all of the subscripts of this getelementptr instruction
1041 // to determine if we can prove known low zero bits.
1042 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1043 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1044 ComputeMaskedBits(I->getOperand(0), LocalMask,
1045 LocalKnownZero, LocalKnownOne, Depth+1);
1046 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1047
1048 gep_type_iterator GTI = gep_type_begin(I);
1049 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1050 Value *Index = I->getOperand(i);
1051 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1052 // Handle struct member offset arithmetic.
1053 if (!TD) return;
1054 const StructLayout *SL = TD->getStructLayout(STy);
1055 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1056 uint64_t Offset = SL->getElementOffset(Idx);
1057 TrailZ = std::min(TrailZ,
1058 CountTrailingZeros_64(Offset));
1059 } else {
1060 // Handle array index arithmetic.
1061 const Type *IndexedTy = GTI.getIndexedType();
1062 if (!IndexedTy->isSized()) return;
1063 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1064 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1065 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1066 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1067 ComputeMaskedBits(Index, LocalMask,
1068 LocalKnownZero, LocalKnownOne, Depth+1);
1069 TrailZ = std::min(TrailZ,
1070 CountTrailingZeros_64(TypeSize) +
1071 LocalKnownZero.countTrailingOnes());
1072 }
1073 }
1074
1075 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1076 break;
1077 }
1078 case Instruction::PHI: {
1079 PHINode *P = cast<PHINode>(I);
1080 // Handle the case of a simple two-predecessor recurrence PHI.
1081 // There's a lot more that could theoretically be done here, but
1082 // this is sufficient to catch some interesting cases.
1083 if (P->getNumIncomingValues() == 2) {
1084 for (unsigned i = 0; i != 2; ++i) {
1085 Value *L = P->getIncomingValue(i);
1086 Value *R = P->getIncomingValue(!i);
1087 User *LU = dyn_cast<User>(L);
1088 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1089 // Check for operations that have the property that if
1090 // both their operands have low zero bits, the result
1091 // will have low zero bits.
1092 if (Opcode == Instruction::Add ||
1093 Opcode == Instruction::Sub ||
1094 Opcode == Instruction::And ||
1095 Opcode == Instruction::Or ||
1096 Opcode == Instruction::Mul) {
1097 Value *LL = LU->getOperand(0);
1098 Value *LR = LU->getOperand(1);
1099 // Find a recurrence.
1100 if (LL == I)
1101 L = LR;
1102 else if (LR == I)
1103 L = LL;
1104 else
1105 break;
1106 // Ok, we have a PHI of the form L op= R. Check for low
1107 // zero bits.
1108 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1109 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1110 Mask2 = APInt::getLowBitsSet(BitWidth,
1111 KnownZero2.countTrailingOnes());
1112 KnownOne2.clear();
1113 KnownZero2.clear();
1114 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1115 KnownZero = Mask &
1116 APInt::getLowBitsSet(BitWidth,
1117 KnownZero2.countTrailingOnes());
1118 break;
1119 }
1120 }
1121 }
1122 break;
1123 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001124 case Instruction::Call:
1125 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1126 switch (II->getIntrinsicID()) {
1127 default: break;
1128 case Intrinsic::ctpop:
1129 case Intrinsic::ctlz:
1130 case Intrinsic::cttz: {
1131 unsigned LowBits = Log2_32(BitWidth)+1;
1132 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1133 break;
1134 }
1135 }
1136 }
1137 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001138 }
1139}
1140
Reid Spencere7816b52007-03-08 01:52:58 +00001141/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1142/// this predicate to simplify operations downstream. Mask is known to be zero
1143/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001144bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1145 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001146 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001147 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1148 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1149 return (KnownZero & Mask) == Mask;
1150}
1151
Chris Lattner255d8912006-02-11 09:31:47 +00001152/// ShrinkDemandedConstant - Check to see if the specified operand of the
1153/// specified instruction is a constant integer. If so, check to see if there
1154/// are any bits set in the constant that are not demanded. If so, shrink the
1155/// constant and return true.
1156static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001157 APInt Demanded) {
1158 assert(I && "No instruction?");
1159 assert(OpNo < I->getNumOperands() && "Operand index too large");
1160
1161 // If the operand is not a constant integer, nothing to do.
1162 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1163 if (!OpC) return false;
1164
1165 // If there are no bits set that aren't demanded, nothing to do.
1166 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1167 if ((~Demanded & OpC->getValue()) == 0)
1168 return false;
1169
1170 // This instruction is producing bits that are not demanded. Shrink the RHS.
1171 Demanded &= OpC->getValue();
1172 I->setOperand(OpNo, ConstantInt::get(Demanded));
1173 return true;
1174}
1175
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001176// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1177// set of known zero and one bits, compute the maximum and minimum values that
1178// could have the specified known zero and known one bits, returning them in
1179// min/max.
1180static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001181 const APInt& KnownZero,
1182 const APInt& KnownOne,
1183 APInt& Min, APInt& Max) {
1184 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1185 assert(KnownZero.getBitWidth() == BitWidth &&
1186 KnownOne.getBitWidth() == BitWidth &&
1187 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1188 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001189 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001190
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001191 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1192 // bit if it is unknown.
1193 Min = KnownOne;
1194 Max = KnownOne|UnknownBits;
1195
Zhou Sheng4acf1552007-03-28 05:15:57 +00001196 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001197 Min.set(BitWidth-1);
1198 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001199 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001200}
1201
1202// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1203// a set of known zero and one bits, compute the maximum and minimum values that
1204// could have the specified known zero and known one bits, returning them in
1205// min/max.
1206static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001207 const APInt &KnownZero,
1208 const APInt &KnownOne,
1209 APInt &Min, APInt &Max) {
1210 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001211 assert(KnownZero.getBitWidth() == BitWidth &&
1212 KnownOne.getBitWidth() == BitWidth &&
1213 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1214 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001215 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001216
1217 // The minimum value is when the unknown bits are all zeros.
1218 Min = KnownOne;
1219 // The maximum value is when the unknown bits are all ones.
1220 Max = KnownOne|UnknownBits;
1221}
Chris Lattner255d8912006-02-11 09:31:47 +00001222
Reid Spencer8cb68342007-03-12 17:25:59 +00001223/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1224/// value based on the demanded bits. When this function is called, it is known
1225/// that only the bits set in DemandedMask of the result of V are ever used
1226/// downstream. Consequently, depending on the mask and V, it may be possible
1227/// to replace V with a constant or one of its operands. In such cases, this
1228/// function does the replacement and returns true. In all other cases, it
1229/// returns false after analyzing the expression and setting KnownOne and known
1230/// to be one in the expression. KnownZero contains all the bits that are known
1231/// to be zero in the expression. These are provided to potentially allow the
1232/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1233/// the expression. KnownOne and KnownZero always follow the invariant that
1234/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1235/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1236/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1237/// and KnownOne must all be the same.
1238bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1239 APInt& KnownZero, APInt& KnownOne,
1240 unsigned Depth) {
1241 assert(V != 0 && "Null pointer of Value???");
1242 assert(Depth <= 6 && "Limit Search Depth");
1243 uint32_t BitWidth = DemandedMask.getBitWidth();
1244 const IntegerType *VTy = cast<IntegerType>(V->getType());
1245 assert(VTy->getBitWidth() == BitWidth &&
1246 KnownZero.getBitWidth() == BitWidth &&
1247 KnownOne.getBitWidth() == BitWidth &&
1248 "Value *V, DemandedMask, KnownZero and KnownOne \
1249 must have same BitWidth");
1250 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1251 // We know all of the bits for a constant!
1252 KnownOne = CI->getValue() & DemandedMask;
1253 KnownZero = ~KnownOne & DemandedMask;
1254 return false;
1255 }
1256
Zhou Sheng96704452007-03-14 03:21:24 +00001257 KnownZero.clear();
1258 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 if (!V->hasOneUse()) { // Other users may use these bits.
1260 if (Depth != 0) { // Not at the root.
1261 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1262 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1263 return false;
1264 }
1265 // If this is the root being simplified, allow it to have multiple uses,
1266 // just set the DemandedMask to all bits.
1267 DemandedMask = APInt::getAllOnesValue(BitWidth);
1268 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1269 if (V != UndefValue::get(VTy))
1270 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1271 return false;
1272 } else if (Depth == 6) { // Limit search depth.
1273 return false;
1274 }
1275
1276 Instruction *I = dyn_cast<Instruction>(V);
1277 if (!I) return false; // Only analyze instructions.
1278
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1280 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1281 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001282 default:
1283 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1284 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 case Instruction::And:
1286 // If either the LHS or the RHS are Zero, the result is zero.
1287 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1288 RHSKnownZero, RHSKnownOne, Depth+1))
1289 return true;
1290 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1291 "Bits known to be one AND zero?");
1292
1293 // If something is known zero on the RHS, the bits aren't demanded on the
1294 // LHS.
1295 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1296 LHSKnownZero, LHSKnownOne, Depth+1))
1297 return true;
1298 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1299 "Bits known to be one AND zero?");
1300
1301 // If all of the demanded bits are known 1 on one side, return the other.
1302 // These bits cannot contribute to the result of the 'and'.
1303 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1304 (DemandedMask & ~LHSKnownZero))
1305 return UpdateValueUsesWith(I, I->getOperand(0));
1306 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1307 (DemandedMask & ~RHSKnownZero))
1308 return UpdateValueUsesWith(I, I->getOperand(1));
1309
1310 // If all of the demanded bits in the inputs are known zeros, return zero.
1311 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1312 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1313
1314 // If the RHS is a constant, see if we can simplify it.
1315 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1316 return UpdateValueUsesWith(I, I);
1317
1318 // Output known-1 bits are only known if set in both the LHS & RHS.
1319 RHSKnownOne &= LHSKnownOne;
1320 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1321 RHSKnownZero |= LHSKnownZero;
1322 break;
1323 case Instruction::Or:
1324 // If either the LHS or the RHS are One, the result is One.
1325 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1326 RHSKnownZero, RHSKnownOne, Depth+1))
1327 return true;
1328 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1329 "Bits known to be one AND zero?");
1330 // If something is known one on the RHS, the bits aren't demanded on the
1331 // LHS.
1332 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1333 LHSKnownZero, LHSKnownOne, Depth+1))
1334 return true;
1335 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1336 "Bits known to be one AND zero?");
1337
1338 // If all of the demanded bits are known zero on one side, return the other.
1339 // These bits cannot contribute to the result of the 'or'.
1340 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1341 (DemandedMask & ~LHSKnownOne))
1342 return UpdateValueUsesWith(I, I->getOperand(0));
1343 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1344 (DemandedMask & ~RHSKnownOne))
1345 return UpdateValueUsesWith(I, I->getOperand(1));
1346
1347 // If all of the potentially set bits on one side are known to be set on
1348 // the other side, just use the 'other' side.
1349 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1350 (DemandedMask & (~RHSKnownZero)))
1351 return UpdateValueUsesWith(I, I->getOperand(0));
1352 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1353 (DemandedMask & (~LHSKnownZero)))
1354 return UpdateValueUsesWith(I, I->getOperand(1));
1355
1356 // If the RHS is a constant, see if we can simplify it.
1357 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1358 return UpdateValueUsesWith(I, I);
1359
1360 // Output known-0 bits are only known if clear in both the LHS & RHS.
1361 RHSKnownZero &= LHSKnownZero;
1362 // Output known-1 are known to be set if set in either the LHS | RHS.
1363 RHSKnownOne |= LHSKnownOne;
1364 break;
1365 case Instruction::Xor: {
1366 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1367 RHSKnownZero, RHSKnownOne, Depth+1))
1368 return true;
1369 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1370 "Bits known to be one AND zero?");
1371 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1372 LHSKnownZero, LHSKnownOne, Depth+1))
1373 return true;
1374 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1375 "Bits known to be one AND zero?");
1376
1377 // If all of the demanded bits are known zero on one side, return the other.
1378 // These bits cannot contribute to the result of the 'xor'.
1379 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1380 return UpdateValueUsesWith(I, I->getOperand(0));
1381 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1382 return UpdateValueUsesWith(I, I->getOperand(1));
1383
1384 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1385 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1386 (RHSKnownOne & LHSKnownOne);
1387 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1388 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1389 (RHSKnownOne & LHSKnownZero);
1390
1391 // If all of the demanded bits are known to be zero on one side or the
1392 // other, turn this into an *inclusive* or.
1393 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1394 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1395 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001396 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001397 I->getName());
1398 InsertNewInstBefore(Or, *I);
1399 return UpdateValueUsesWith(I, Or);
1400 }
1401
1402 // If all of the demanded bits on one side are known, and all of the set
1403 // bits on that side are also known to be set on the other side, turn this
1404 // into an AND, as we know the bits will be cleared.
1405 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1406 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1407 // all known
1408 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1409 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1410 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001411 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +00001412 InsertNewInstBefore(And, *I);
1413 return UpdateValueUsesWith(I, And);
1414 }
1415 }
1416
1417 // If the RHS is a constant, see if we can simplify it.
1418 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1419 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1420 return UpdateValueUsesWith(I, I);
1421
1422 RHSKnownZero = KnownZeroOut;
1423 RHSKnownOne = KnownOneOut;
1424 break;
1425 }
1426 case Instruction::Select:
1427 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1428 RHSKnownZero, RHSKnownOne, Depth+1))
1429 return true;
1430 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1431 LHSKnownZero, LHSKnownOne, Depth+1))
1432 return true;
1433 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1434 "Bits known to be one AND zero?");
1435 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1436 "Bits known to be one AND zero?");
1437
1438 // If the operands are constants, see if we can simplify them.
1439 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1440 return UpdateValueUsesWith(I, I);
1441 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1442 return UpdateValueUsesWith(I, I);
1443
1444 // Only known if known in both the LHS and RHS.
1445 RHSKnownOne &= LHSKnownOne;
1446 RHSKnownZero &= LHSKnownZero;
1447 break;
1448 case Instruction::Trunc: {
1449 uint32_t truncBf =
1450 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001451 DemandedMask.zext(truncBf);
1452 RHSKnownZero.zext(truncBf);
1453 RHSKnownOne.zext(truncBf);
1454 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1455 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001456 return true;
1457 DemandedMask.trunc(BitWidth);
1458 RHSKnownZero.trunc(BitWidth);
1459 RHSKnownOne.trunc(BitWidth);
1460 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1461 "Bits known to be one AND zero?");
1462 break;
1463 }
1464 case Instruction::BitCast:
1465 if (!I->getOperand(0)->getType()->isInteger())
1466 return false;
1467
1468 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1469 RHSKnownZero, RHSKnownOne, Depth+1))
1470 return true;
1471 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1472 "Bits known to be one AND zero?");
1473 break;
1474 case Instruction::ZExt: {
1475 // Compute the bits in the result that are not present in the input.
1476 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001477 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001478
Zhou Shengd48653a2007-03-29 04:45:55 +00001479 DemandedMask.trunc(SrcBitWidth);
1480 RHSKnownZero.trunc(SrcBitWidth);
1481 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001482 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1483 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001484 return true;
1485 DemandedMask.zext(BitWidth);
1486 RHSKnownZero.zext(BitWidth);
1487 RHSKnownOne.zext(BitWidth);
1488 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1489 "Bits known to be one AND zero?");
1490 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001491 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001492 break;
1493 }
1494 case Instruction::SExt: {
1495 // Compute the bits in the result that are not present in the input.
1496 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001497 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001498
Reid Spencer8cb68342007-03-12 17:25:59 +00001499 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001500 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001501
Zhou Sheng01542f32007-03-29 02:26:30 +00001502 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001503 // If any of the sign extended bits are demanded, we know that the sign
1504 // bit is demanded.
1505 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001506 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001507
Zhou Shengd48653a2007-03-29 04:45:55 +00001508 InputDemandedBits.trunc(SrcBitWidth);
1509 RHSKnownZero.trunc(SrcBitWidth);
1510 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001511 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1512 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001513 return true;
1514 InputDemandedBits.zext(BitWidth);
1515 RHSKnownZero.zext(BitWidth);
1516 RHSKnownOne.zext(BitWidth);
1517 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1518 "Bits known to be one AND zero?");
1519
1520 // If the sign bit of the input is known set or clear, then we know the
1521 // top bits of the result.
1522
1523 // If the input sign bit is known zero, or if the NewBits are not demanded
1524 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001525 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001526 {
1527 // Convert to ZExt cast
1528 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1529 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001530 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001531 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001532 }
1533 break;
1534 }
1535 case Instruction::Add: {
1536 // Figure out what the input bits are. If the top bits of the and result
1537 // are not demanded, then the add doesn't demand them from its input
1538 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001539 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001540
1541 // If there is a constant on the RHS, there are a variety of xformations
1542 // we can do.
1543 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1544 // If null, this should be simplified elsewhere. Some of the xforms here
1545 // won't work if the RHS is zero.
1546 if (RHS->isZero())
1547 break;
1548
1549 // If the top bit of the output is demanded, demand everything from the
1550 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001551 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001552
1553 // Find information about known zero/one bits in the input.
1554 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1555 LHSKnownZero, LHSKnownOne, Depth+1))
1556 return true;
1557
1558 // If the RHS of the add has bits set that can't affect the input, reduce
1559 // the constant.
1560 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1561 return UpdateValueUsesWith(I, I);
1562
1563 // Avoid excess work.
1564 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1565 break;
1566
1567 // Turn it into OR if input bits are zero.
1568 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1569 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001570 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001571 I->getName());
1572 InsertNewInstBefore(Or, *I);
1573 return UpdateValueUsesWith(I, Or);
1574 }
1575
1576 // We can say something about the output known-zero and known-one bits,
1577 // depending on potential carries from the input constant and the
1578 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1579 // bits set and the RHS constant is 0x01001, then we know we have a known
1580 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1581
1582 // To compute this, we first compute the potential carry bits. These are
1583 // the bits which may be modified. I'm not aware of a better way to do
1584 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001585 const APInt& RHSVal = RHS->getValue();
1586 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001587
1588 // Now that we know which bits have carries, compute the known-1/0 sets.
1589
1590 // Bits are known one if they are known zero in one operand and one in the
1591 // other, and there is no input carry.
1592 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1593 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1594
1595 // Bits are known zero if they are known zero in both operands and there
1596 // is no input carry.
1597 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1598 } else {
1599 // If the high-bits of this ADD are not demanded, then it does not demand
1600 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001601 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001602 // Right fill the mask of bits for this ADD to demand the most
1603 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001604 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001605 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1606 LHSKnownZero, LHSKnownOne, Depth+1))
1607 return true;
1608 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1609 LHSKnownZero, LHSKnownOne, Depth+1))
1610 return true;
1611 }
1612 }
1613 break;
1614 }
1615 case Instruction::Sub:
1616 // If the high-bits of this SUB are not demanded, then it does not demand
1617 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001618 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001619 // Right fill the mask of bits for this SUB to demand the most
1620 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001621 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001622 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001623 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1624 LHSKnownZero, LHSKnownOne, Depth+1))
1625 return true;
1626 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1627 LHSKnownZero, LHSKnownOne, Depth+1))
1628 return true;
1629 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001630 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1631 // the known zeros and ones.
1632 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001633 break;
1634 case Instruction::Shl:
1635 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001636 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001637 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1638 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001639 RHSKnownZero, RHSKnownOne, Depth+1))
1640 return true;
1641 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1642 "Bits known to be one AND zero?");
1643 RHSKnownZero <<= ShiftAmt;
1644 RHSKnownOne <<= ShiftAmt;
1645 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001646 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001647 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001648 }
1649 break;
1650 case Instruction::LShr:
1651 // For a logical shift right
1652 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001653 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001654
Reid Spencer8cb68342007-03-12 17:25:59 +00001655 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001656 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1657 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001658 RHSKnownZero, RHSKnownOne, Depth+1))
1659 return true;
1660 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1661 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001662 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1663 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001664 if (ShiftAmt) {
1665 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001666 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001667 RHSKnownZero |= HighBits; // high bits known zero.
1668 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001669 }
1670 break;
1671 case Instruction::AShr:
1672 // If this is an arithmetic shift right and only the low-bit is set, we can
1673 // always convert this into a logical shr, even if the shift amount is
1674 // variable. The low bit of the shift cannot be an input sign bit unless
1675 // the shift amount is >= the size of the datatype, which is undefined.
1676 if (DemandedMask == 1) {
1677 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001678 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001679 I->getOperand(0), I->getOperand(1), I->getName());
1680 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1681 return UpdateValueUsesWith(I, NewVal);
1682 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001683
1684 // If the sign bit is the only bit demanded by this ashr, then there is no
1685 // need to do it, the shift doesn't change the high bit.
1686 if (DemandedMask.isSignBit())
1687 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001688
1689 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001690 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001691
Reid Spencer8cb68342007-03-12 17:25:59 +00001692 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001693 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001694 // If any of the "high bits" are demanded, we should set the sign bit as
1695 // demanded.
1696 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1697 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001698 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001699 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001700 RHSKnownZero, RHSKnownOne, Depth+1))
1701 return true;
1702 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1703 "Bits known to be one AND zero?");
1704 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001705 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001706 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1707 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1708
1709 // Handle the sign bits.
1710 APInt SignBit(APInt::getSignBit(BitWidth));
1711 // Adjust to where it is now in the mask.
1712 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1713
1714 // If the input sign bit is known to be zero, or if none of the top bits
1715 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001716 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001717 (HighBits & ~DemandedMask) == HighBits) {
1718 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001719 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001720 I->getOperand(0), SA, I->getName());
1721 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1722 return UpdateValueUsesWith(I, NewVal);
1723 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1724 RHSKnownOne |= HighBits;
1725 }
1726 }
1727 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001728 case Instruction::SRem:
1729 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1730 APInt RA = Rem->getValue();
1731 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001732 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001733 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1734 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1735 LHSKnownZero, LHSKnownOne, Depth+1))
1736 return true;
1737
1738 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1739 LHSKnownZero |= ~LowBits;
1740 else if (LHSKnownOne[BitWidth-1])
1741 LHSKnownOne |= ~LowBits;
1742
1743 KnownZero |= LHSKnownZero & DemandedMask;
1744 KnownOne |= LHSKnownOne & DemandedMask;
1745
1746 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1747 }
1748 }
1749 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001750 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001751 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1752 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001753 if (RA.isPowerOf2()) {
1754 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001755 APInt Mask2 = LowBits & DemandedMask;
1756 KnownZero |= ~LowBits & DemandedMask;
1757 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1758 KnownZero, KnownOne, Depth+1))
1759 return true;
1760
1761 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001762 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001763 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001764 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001765
1766 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1767 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001768 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1769 KnownZero2, KnownOne2, Depth+1))
1770 return true;
1771
Dan Gohman23e8b712008-04-28 17:02:21 +00001772 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001773 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001774 KnownZero2, KnownOne2, Depth+1))
1775 return true;
1776
1777 Leaders = std::max(Leaders,
1778 KnownZero2.countLeadingOnes());
1779 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001780 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001781 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001782 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001783
1784 // If the client is only demanding bits that we know, return the known
1785 // constant.
1786 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1787 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1788 return false;
1789}
1790
Chris Lattner867b99f2006-10-05 06:55:50 +00001791
1792/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1793/// 64 or fewer elements. DemandedElts contains the set of elements that are
1794/// actually used by the caller. This method analyzes which elements of the
1795/// operand are undef and returns that information in UndefElts.
1796///
1797/// If the information about demanded elements can be used to simplify the
1798/// operation, the operation is simplified, then the resultant value is
1799/// returned. This returns null if no change was made.
1800Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1801 uint64_t &UndefElts,
1802 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001803 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001804 assert(VWidth <= 64 && "Vector too wide to analyze!");
1805 uint64_t EltMask = ~0ULL >> (64-VWidth);
1806 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1807 "Invalid DemandedElts!");
1808
1809 if (isa<UndefValue>(V)) {
1810 // If the entire vector is undefined, just return this info.
1811 UndefElts = EltMask;
1812 return 0;
1813 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1814 UndefElts = EltMask;
1815 return UndefValue::get(V->getType());
1816 }
1817
1818 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001819 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1820 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001821 Constant *Undef = UndefValue::get(EltTy);
1822
1823 std::vector<Constant*> Elts;
1824 for (unsigned i = 0; i != VWidth; ++i)
1825 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1826 Elts.push_back(Undef);
1827 UndefElts |= (1ULL << i);
1828 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1829 Elts.push_back(Undef);
1830 UndefElts |= (1ULL << i);
1831 } else { // Otherwise, defined.
1832 Elts.push_back(CP->getOperand(i));
1833 }
1834
1835 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001836 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001837 return NewCP != CP ? NewCP : 0;
1838 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001839 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001840 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001841 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001842 Constant *Zero = Constant::getNullValue(EltTy);
1843 Constant *Undef = UndefValue::get(EltTy);
1844 std::vector<Constant*> Elts;
1845 for (unsigned i = 0; i != VWidth; ++i)
1846 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1847 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001848 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001849 }
1850
1851 if (!V->hasOneUse()) { // Other users may use these bits.
1852 if (Depth != 0) { // Not at the root.
1853 // TODO: Just compute the UndefElts information recursively.
1854 return false;
1855 }
1856 return false;
1857 } else if (Depth == 10) { // Limit search depth.
1858 return false;
1859 }
1860
1861 Instruction *I = dyn_cast<Instruction>(V);
1862 if (!I) return false; // Only analyze instructions.
1863
1864 bool MadeChange = false;
1865 uint64_t UndefElts2;
1866 Value *TmpV;
1867 switch (I->getOpcode()) {
1868 default: break;
1869
1870 case Instruction::InsertElement: {
1871 // If this is a variable index, we don't know which element it overwrites.
1872 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001873 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001874 if (Idx == 0) {
1875 // Note that we can't propagate undef elt info, because we don't know
1876 // which elt is getting updated.
1877 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1878 UndefElts2, Depth+1);
1879 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1880 break;
1881 }
1882
1883 // If this is inserting an element that isn't demanded, remove this
1884 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001885 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001886 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1887 return AddSoonDeadInstToWorklist(*I, 0);
1888
1889 // Otherwise, the element inserted overwrites whatever was there, so the
1890 // input demanded set is simpler than the output set.
1891 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1892 DemandedElts & ~(1ULL << IdxNo),
1893 UndefElts, Depth+1);
1894 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1895
1896 // The inserted element is defined.
1897 UndefElts |= 1ULL << IdxNo;
1898 break;
1899 }
Chris Lattner69878332007-04-14 22:29:23 +00001900 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001901 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001902 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1903 if (!VTy) break;
1904 unsigned InVWidth = VTy->getNumElements();
1905 uint64_t InputDemandedElts = 0;
1906 unsigned Ratio;
1907
1908 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001909 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001910 // elements as are demanded of us.
1911 Ratio = 1;
1912 InputDemandedElts = DemandedElts;
1913 } else if (VWidth > InVWidth) {
1914 // Untested so far.
1915 break;
1916
1917 // If there are more elements in the result than there are in the source,
1918 // then an input element is live if any of the corresponding output
1919 // elements are live.
1920 Ratio = VWidth/InVWidth;
1921 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1922 if (DemandedElts & (1ULL << OutIdx))
1923 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1924 }
1925 } else {
1926 // Untested so far.
1927 break;
1928
1929 // If there are more elements in the source than there are in the result,
1930 // then an input element is live if the corresponding output element is
1931 // live.
1932 Ratio = InVWidth/VWidth;
1933 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1934 if (DemandedElts & (1ULL << InIdx/Ratio))
1935 InputDemandedElts |= 1ULL << InIdx;
1936 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001937
Chris Lattner69878332007-04-14 22:29:23 +00001938 // div/rem demand all inputs, because they don't want divide by zero.
1939 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1940 UndefElts2, Depth+1);
1941 if (TmpV) {
1942 I->setOperand(0, TmpV);
1943 MadeChange = true;
1944 }
1945
1946 UndefElts = UndefElts2;
1947 if (VWidth > InVWidth) {
1948 assert(0 && "Unimp");
1949 // If there are more elements in the result than there are in the source,
1950 // then an output element is undef if the corresponding input element is
1951 // undef.
1952 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1953 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1954 UndefElts |= 1ULL << OutIdx;
1955 } else if (VWidth < InVWidth) {
1956 assert(0 && "Unimp");
1957 // If there are more elements in the source than there are in the result,
1958 // then a result element is undef if all of the corresponding input
1959 // elements are undef.
1960 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1961 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1962 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1963 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1964 }
1965 break;
1966 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001967 case Instruction::And:
1968 case Instruction::Or:
1969 case Instruction::Xor:
1970 case Instruction::Add:
1971 case Instruction::Sub:
1972 case Instruction::Mul:
1973 // div/rem demand all inputs, because they don't want divide by zero.
1974 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1975 UndefElts, Depth+1);
1976 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1977 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1978 UndefElts2, Depth+1);
1979 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1980
1981 // Output elements are undefined if both are undefined. Consider things
1982 // like undef&0. The result is known zero, not undef.
1983 UndefElts &= UndefElts2;
1984 break;
1985
1986 case Instruction::Call: {
1987 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1988 if (!II) break;
1989 switch (II->getIntrinsicID()) {
1990 default: break;
1991
1992 // Binary vector operations that work column-wise. A dest element is a
1993 // function of the corresponding input elements from the two inputs.
1994 case Intrinsic::x86_sse_sub_ss:
1995 case Intrinsic::x86_sse_mul_ss:
1996 case Intrinsic::x86_sse_min_ss:
1997 case Intrinsic::x86_sse_max_ss:
1998 case Intrinsic::x86_sse2_sub_sd:
1999 case Intrinsic::x86_sse2_mul_sd:
2000 case Intrinsic::x86_sse2_min_sd:
2001 case Intrinsic::x86_sse2_max_sd:
2002 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2003 UndefElts, Depth+1);
2004 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2005 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2006 UndefElts2, Depth+1);
2007 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2008
2009 // If only the low elt is demanded and this is a scalarizable intrinsic,
2010 // scalarize it now.
2011 if (DemandedElts == 1) {
2012 switch (II->getIntrinsicID()) {
2013 default: break;
2014 case Intrinsic::x86_sse_sub_ss:
2015 case Intrinsic::x86_sse_mul_ss:
2016 case Intrinsic::x86_sse2_sub_sd:
2017 case Intrinsic::x86_sse2_mul_sd:
2018 // TODO: Lower MIN/MAX/ABS/etc
2019 Value *LHS = II->getOperand(1);
2020 Value *RHS = II->getOperand(2);
2021 // Extract the element as scalars.
2022 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2023 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2024
2025 switch (II->getIntrinsicID()) {
2026 default: assert(0 && "Case stmts out of sync!");
2027 case Intrinsic::x86_sse_sub_ss:
2028 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002029 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002030 II->getName()), *II);
2031 break;
2032 case Intrinsic::x86_sse_mul_ss:
2033 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002034 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002035 II->getName()), *II);
2036 break;
2037 }
2038
2039 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002040 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2041 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002042 InsertNewInstBefore(New, *II);
2043 AddSoonDeadInstToWorklist(*II, 0);
2044 return New;
2045 }
2046 }
2047
2048 // Output elements are undefined if both are undefined. Consider things
2049 // like undef&0. The result is known zero, not undef.
2050 UndefElts &= UndefElts2;
2051 break;
2052 }
2053 break;
2054 }
2055 }
2056 return MadeChange ? I : 0;
2057}
2058
Chris Lattner564a7272003-08-13 19:01:45 +00002059/// AssociativeOpt - Perform an optimization on an associative operator. This
2060/// function is designed to check a chain of associative operators for a
2061/// potential to apply a certain optimization. Since the optimization may be
2062/// applicable if the expression was reassociated, this checks the chain, then
2063/// reassociates the expression as necessary to expose the optimization
2064/// opportunity. This makes use of a special Functor, which must define
2065/// 'shouldApply' and 'apply' methods.
2066///
2067template<typename Functor>
2068Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2069 unsigned Opcode = Root.getOpcode();
2070 Value *LHS = Root.getOperand(0);
2071
2072 // Quick check, see if the immediate LHS matches...
2073 if (F.shouldApply(LHS))
2074 return F.apply(Root);
2075
2076 // Otherwise, if the LHS is not of the same opcode as the root, return.
2077 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002078 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002079 // Should we apply this transform to the RHS?
2080 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2081
2082 // If not to the RHS, check to see if we should apply to the LHS...
2083 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2084 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2085 ShouldApply = true;
2086 }
2087
2088 // If the functor wants to apply the optimization to the RHS of LHSI,
2089 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2090 if (ShouldApply) {
2091 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002092
Chris Lattner564a7272003-08-13 19:01:45 +00002093 // Now all of the instructions are in the current basic block, go ahead
2094 // and perform the reassociation.
2095 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2096
2097 // First move the selected RHS to the LHS of the root...
2098 Root.setOperand(0, LHSI->getOperand(1));
2099
2100 // Make what used to be the LHS of the root be the user of the root...
2101 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002102 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002103 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2104 return 0;
2105 }
Chris Lattner65725312004-04-16 18:08:07 +00002106 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002107 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002108 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2109 BasicBlock::iterator ARI = &Root; ++ARI;
2110 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2111 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002112
2113 // Now propagate the ExtraOperand down the chain of instructions until we
2114 // get to LHSI.
2115 while (TmpLHSI != LHSI) {
2116 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002117 // Move the instruction to immediately before the chain we are
2118 // constructing to avoid breaking dominance properties.
2119 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2120 BB->getInstList().insert(ARI, NextLHSI);
2121 ARI = NextLHSI;
2122
Chris Lattner564a7272003-08-13 19:01:45 +00002123 Value *NextOp = NextLHSI->getOperand(1);
2124 NextLHSI->setOperand(1, ExtraOperand);
2125 TmpLHSI = NextLHSI;
2126 ExtraOperand = NextOp;
2127 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002128
Chris Lattner564a7272003-08-13 19:01:45 +00002129 // Now that the instructions are reassociated, have the functor perform
2130 // the transformation...
2131 return F.apply(Root);
2132 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002133
Chris Lattner564a7272003-08-13 19:01:45 +00002134 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2135 }
2136 return 0;
2137}
2138
Dan Gohman844731a2008-05-13 00:00:25 +00002139namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002140
2141// AddRHS - Implements: X + X --> X << 1
2142struct AddRHS {
2143 Value *RHS;
2144 AddRHS(Value *rhs) : RHS(rhs) {}
2145 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2146 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002147 return BinaryOperator::CreateShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00002148 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002149 }
2150};
2151
2152// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2153// iff C1&C2 == 0
2154struct AddMaskingAnd {
2155 Constant *C2;
2156 AddMaskingAnd(Constant *c) : C2(c) {}
2157 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002158 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002159 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002160 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002161 }
2162 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002163 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002164 }
2165};
2166
Dan Gohman844731a2008-05-13 00:00:25 +00002167}
2168
Chris Lattner6e7ba452005-01-01 16:22:27 +00002169static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002170 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002171 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002172 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002173 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002174
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002175 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002176 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002177 }
2178
Chris Lattner2eefe512004-04-09 19:05:30 +00002179 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002180 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2181 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002182
Chris Lattner2eefe512004-04-09 19:05:30 +00002183 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2184 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002185 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2186 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002187 }
2188
2189 Value *Op0 = SO, *Op1 = ConstOperand;
2190 if (!ConstIsRHS)
2191 std::swap(Op0, Op1);
2192 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002193 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002194 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002195 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002196 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002197 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002198 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002199 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002200 abort();
2201 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002202 return IC->InsertNewInstBefore(New, I);
2203}
2204
2205// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2206// constant as the other operand, try to fold the binary operator into the
2207// select arguments. This also works for Cast instructions, which obviously do
2208// not have a second operand.
2209static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2210 InstCombiner *IC) {
2211 // Don't modify shared select instructions
2212 if (!SI->hasOneUse()) return 0;
2213 Value *TV = SI->getOperand(1);
2214 Value *FV = SI->getOperand(2);
2215
2216 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002217 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002218 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002219
Chris Lattner6e7ba452005-01-01 16:22:27 +00002220 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2221 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2222
Gabor Greif051a9502008-04-06 20:25:17 +00002223 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2224 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002225 }
2226 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002227}
2228
Chris Lattner4e998b22004-09-29 05:07:12 +00002229
2230/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2231/// node as operand #0, see if we can fold the instruction into the PHI (which
2232/// is only possible if all operands to the PHI are constants).
2233Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2234 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002235 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002236 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002237
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002238 // Check to see if all of the operands of the PHI are constants. If there is
2239 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002240 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002241 BasicBlock *NonConstBB = 0;
2242 for (unsigned i = 0; i != NumPHIValues; ++i)
2243 if (!isa<Constant>(PN->getIncomingValue(i))) {
2244 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002245 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002246 NonConstBB = PN->getIncomingBlock(i);
2247
2248 // If the incoming non-constant value is in I's block, we have an infinite
2249 // loop.
2250 if (NonConstBB == I.getParent())
2251 return 0;
2252 }
2253
2254 // If there is exactly one non-constant value, we can insert a copy of the
2255 // operation in that block. However, if this is a critical edge, we would be
2256 // inserting the computation one some other paths (e.g. inside a loop). Only
2257 // do this if the pred block is unconditionally branching into the phi block.
2258 if (NonConstBB) {
2259 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2260 if (!BI || !BI->isUnconditional()) return 0;
2261 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002262
2263 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002264 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002265 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002266 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002267 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002268
2269 // Next, add all of the operands to the PHI.
2270 if (I.getNumOperands() == 2) {
2271 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002272 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002273 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002274 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002275 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2276 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2277 else
2278 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002279 } else {
2280 assert(PN->getIncomingBlock(i) == NonConstBB);
2281 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002282 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002283 PN->getIncomingValue(i), C, "phitmp",
2284 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002285 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002286 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002287 CI->getPredicate(),
2288 PN->getIncomingValue(i), C, "phitmp",
2289 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002290 else
2291 assert(0 && "Unknown binop!");
2292
Chris Lattnerdbab3862007-03-02 21:28:56 +00002293 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002294 }
2295 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002296 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002297 } else {
2298 CastInst *CI = cast<CastInst>(&I);
2299 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002300 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002301 Value *InV;
2302 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002303 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002304 } else {
2305 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002306 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002307 I.getType(), "phitmp",
2308 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002309 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002310 }
2311 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002312 }
2313 }
2314 return ReplaceInstUsesWith(I, NewPN);
2315}
2316
Chris Lattner2454a2e2008-01-29 06:52:45 +00002317
2318/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2319/// value is never equal to -0.0.
2320///
2321/// Note that this function will need to be revisited when we support nondefault
2322/// rounding modes!
2323///
2324static bool CannotBeNegativeZero(const Value *V) {
2325 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2326 return !CFP->getValueAPF().isNegZero();
2327
2328 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2329 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2330 if (I->getOpcode() == Instruction::Add &&
2331 isa<ConstantFP>(I->getOperand(1)) &&
2332 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2333 return true;
2334
2335 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2336 if (II->getIntrinsicID() == Intrinsic::sqrt)
2337 return CannotBeNegativeZero(II->getOperand(1));
2338
2339 if (const CallInst *CI = dyn_cast<CallInst>(I))
2340 if (const Function *F = CI->getCalledFunction()) {
2341 if (F->isDeclaration()) {
2342 switch (F->getNameLen()) {
2343 case 3: // abs(x) != -0.0
2344 if (!strcmp(F->getNameStart(), "abs")) return true;
2345 break;
2346 case 4: // abs[lf](x) != -0.0
2347 if (!strcmp(F->getNameStart(), "absf")) return true;
2348 if (!strcmp(F->getNameStart(), "absl")) return true;
2349 break;
2350 }
2351 }
2352 }
2353 }
2354
2355 return false;
2356}
2357
2358
Chris Lattner7e708292002-06-25 16:13:24 +00002359Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002360 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002361 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002362
Chris Lattner66331a42004-04-10 22:01:55 +00002363 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002364 // X + undef -> undef
2365 if (isa<UndefValue>(RHS))
2366 return ReplaceInstUsesWith(I, RHS);
2367
Chris Lattner66331a42004-04-10 22:01:55 +00002368 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002369 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002370 if (RHSC->isNullValue())
2371 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002372 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002373 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2374 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002375 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002376 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002377
Chris Lattner66331a42004-04-10 22:01:55 +00002378 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002379 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002380 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002381 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002382 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002383 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002384
2385 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2386 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002387 if (!isa<VectorType>(I.getType())) {
2388 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2389 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2390 KnownZero, KnownOne))
2391 return &I;
2392 }
Chris Lattner66331a42004-04-10 22:01:55 +00002393 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002394
2395 if (isa<PHINode>(LHS))
2396 if (Instruction *NV = FoldOpIntoPhi(I))
2397 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002398
Chris Lattner4f637d42006-01-06 17:59:59 +00002399 ConstantInt *XorRHS = 0;
2400 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002401 if (isa<ConstantInt>(RHSC) &&
2402 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002403 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002404 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002405
Zhou Sheng4351c642007-04-02 08:20:41 +00002406 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002407 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2408 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002409 do {
2410 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002411 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2412 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002413 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2414 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002415 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002416 if (!MaskedValueIsZero(XorLHS,
2417 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002418 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002419 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002420 }
2421 }
2422 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002423 C0080Val = APIntOps::lshr(C0080Val, Size);
2424 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2425 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002426
Reid Spencer35c38852007-03-28 01:36:16 +00002427 // FIXME: This shouldn't be necessary. When the backends can handle types
2428 // with funny bit widths then this whole cascade of if statements should
2429 // be removed. It is just here to get the size of the "middle" type back
2430 // up to something that the back ends can handle.
2431 const Type *MiddleType = 0;
2432 switch (Size) {
2433 default: break;
2434 case 32: MiddleType = Type::Int32Ty; break;
2435 case 16: MiddleType = Type::Int16Ty; break;
2436 case 8: MiddleType = Type::Int8Ty; break;
2437 }
2438 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002439 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002440 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002441 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002442 }
2443 }
Chris Lattner66331a42004-04-10 22:01:55 +00002444 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002445
Chris Lattner564a7272003-08-13 19:01:45 +00002446 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002447 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002448 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002449
2450 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2451 if (RHSI->getOpcode() == Instruction::Sub)
2452 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2453 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2454 }
2455 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2456 if (LHSI->getOpcode() == Instruction::Sub)
2457 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2458 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2459 }
Robert Bocchino71698282004-07-27 21:02:21 +00002460 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002461
Chris Lattner5c4afb92002-05-08 22:46:53 +00002462 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002463 // -A + -B --> -(A + B)
2464 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002465 if (LHS->getType()->isIntOrIntVector()) {
2466 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002467 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002468 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002469 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002470 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002471 }
2472
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002473 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002474 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002475
2476 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002477 if (!isa<Constant>(RHS))
2478 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002479 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002480
Misha Brukmanfd939082005-04-21 23:48:37 +00002481
Chris Lattner50af16a2004-11-13 19:50:12 +00002482 ConstantInt *C2;
2483 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2484 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002485 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002486
2487 // X*C1 + X*C2 --> X * (C1+C2)
2488 ConstantInt *C1;
2489 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002490 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002491 }
2492
2493 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002494 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002495 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002496
Chris Lattnere617c9e2007-01-05 02:17:46 +00002497 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002498 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2499 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002500
Chris Lattnerad3448c2003-02-18 19:57:07 +00002501
Chris Lattner564a7272003-08-13 19:01:45 +00002502 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002503 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002504 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2505 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002506
2507 // A+B --> A|B iff A and B have no bits set in common.
2508 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2509 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2510 APInt LHSKnownOne(IT->getBitWidth(), 0);
2511 APInt LHSKnownZero(IT->getBitWidth(), 0);
2512 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2513 if (LHSKnownZero != 0) {
2514 APInt RHSKnownOne(IT->getBitWidth(), 0);
2515 APInt RHSKnownZero(IT->getBitWidth(), 0);
2516 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2517
2518 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002519 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002520 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002521 }
2522 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002523
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002524 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002525 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002526 Value *W, *X, *Y, *Z;
2527 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2528 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2529 if (W != Y) {
2530 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002531 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002532 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002533 std::swap(W, X);
2534 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002535 std::swap(Y, Z);
2536 std::swap(W, X);
2537 }
2538 }
2539
2540 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002541 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002542 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002543 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002544 }
2545 }
2546 }
2547
Chris Lattner6b032052003-10-02 15:11:26 +00002548 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002549 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002550 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002551 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002552
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002553 // (X & FF00) + xx00 -> (X+xx00) & FF00
2554 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002555 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002556 if (Anded == CRHS) {
2557 // See if all bits from the first bit set in the Add RHS up are included
2558 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002559 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002560
2561 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002562 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002563
2564 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002565 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002566
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002567 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2568 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002569 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002570 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002571 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002572 }
2573 }
2574 }
2575
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002576 // Try to fold constant add into select arguments.
2577 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002578 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002579 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002580 }
2581
Reid Spencer1628cec2006-10-26 06:15:43 +00002582 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002583 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002584 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002585 CastInst *CI = dyn_cast<CastInst>(LHS);
2586 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002587 if (!CI) {
2588 CI = dyn_cast<CastInst>(RHS);
2589 Other = LHS;
2590 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002591 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002592 (CI->getType()->getPrimitiveSizeInBits() ==
2593 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002594 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002595 unsigned AS =
2596 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002597 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2598 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002599 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002600 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002601 }
2602 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002603
Chris Lattner42790482007-12-20 01:56:58 +00002604 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002605 {
2606 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2607 Value *Other = RHS;
2608 if (!SI) {
2609 SI = dyn_cast<SelectInst>(RHS);
2610 Other = LHS;
2611 }
Chris Lattner42790482007-12-20 01:56:58 +00002612 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002613 Value *TV = SI->getTrueValue();
2614 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002615 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002616
2617 // Can we fold the add into the argument of the select?
2618 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002619 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2620 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002621 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002622 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2623 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002624 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002625 }
2626 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002627
2628 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2629 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2630 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2631 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002632
Chris Lattner7e708292002-06-25 16:13:24 +00002633 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002634}
2635
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002636// isSignBit - Return true if the value represented by the constant only has the
2637// highest order bit set.
2638static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002639 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002640 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002641}
2642
Chris Lattner7e708292002-06-25 16:13:24 +00002643Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002644 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002645
Chris Lattner233f7dc2002-08-12 21:17:25 +00002646 if (Op0 == Op1) // sub X, X -> 0
2647 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002648
Chris Lattner233f7dc2002-08-12 21:17:25 +00002649 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002650 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002651 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002652
Chris Lattnere87597f2004-10-16 18:11:37 +00002653 if (isa<UndefValue>(Op0))
2654 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2655 if (isa<UndefValue>(Op1))
2656 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2657
Chris Lattnerd65460f2003-11-05 01:06:05 +00002658 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2659 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002660 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002661 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002662
Chris Lattnerd65460f2003-11-05 01:06:05 +00002663 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002664 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002665 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002666 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002667
Chris Lattner76b7a062007-01-15 07:02:54 +00002668 // -(X >>u 31) -> (X >>s 31)
2669 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002670 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002671 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002672 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002673 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002674 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002675 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002676 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002677 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002678 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002679 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002680 }
2681 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002682 }
2683 else if (SI->getOpcode() == Instruction::AShr) {
2684 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2685 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002686 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002687 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002688 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002689 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002690 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002691 }
2692 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002693 }
2694 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002695 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002696
2697 // Try to fold constant sub into select arguments.
2698 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002699 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002700 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002701
2702 if (isa<PHINode>(Op0))
2703 if (Instruction *NV = FoldOpIntoPhi(I))
2704 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002705 }
2706
Chris Lattner43d84d62005-04-07 16:15:25 +00002707 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2708 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002709 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002710 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002711 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002712 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002713 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002714 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2715 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2716 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002717 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002718 Op1I->getOperand(0));
2719 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002720 }
2721
Chris Lattnerfd059242003-10-15 16:48:29 +00002722 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002723 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2724 // is not used by anyone else...
2725 //
Chris Lattner0517e722004-02-02 20:09:56 +00002726 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002727 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002728 // Swap the two operands of the subexpr...
2729 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2730 Op1I->setOperand(0, IIOp1);
2731 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002732
Chris Lattnera2881962003-02-18 19:28:33 +00002733 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002734 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002735 }
2736
2737 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2738 //
2739 if (Op1I->getOpcode() == Instruction::And &&
2740 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2741 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2742
Chris Lattnerf523d062004-06-09 05:08:07 +00002743 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002744 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2745 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002746 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002747
Reid Spencerac5209e2006-10-16 23:08:08 +00002748 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002749 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002750 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002751 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002752 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002753 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002754 ConstantExpr::getNeg(DivRHS));
2755
Chris Lattnerad3448c2003-02-18 19:57:07 +00002756 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002757 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002758 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002759 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002760 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002761 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002762
2763 // X - ((X / Y) * Y) --> X % Y
2764 if (Op1I->getOpcode() == Instruction::Mul)
2765 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2766 if (Op0 == I->getOperand(0) &&
2767 Op1I->getOperand(1) == I->getOperand(1)) {
2768 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002769 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002770 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002771 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002772 }
Chris Lattner40371712002-05-09 01:29:19 +00002773 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002774 }
Chris Lattnera2881962003-02-18 19:28:33 +00002775
Chris Lattner9919e3d2006-12-02 00:13:08 +00002776 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002777 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002778 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002779 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2780 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2781 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2782 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002783 } else if (Op0I->getOpcode() == Instruction::Sub) {
2784 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002785 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002786 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002787 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002788
Chris Lattner50af16a2004-11-13 19:50:12 +00002789 ConstantInt *C1;
2790 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002791 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002792 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002793
Chris Lattner50af16a2004-11-13 19:50:12 +00002794 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2795 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002796 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002797 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002798 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002799}
2800
Chris Lattnera0141b92007-07-15 20:42:37 +00002801/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2802/// comparison only checks the sign bit. If it only checks the sign bit, set
2803/// TrueIfSigned if the result of the comparison is true when the input value is
2804/// signed.
2805static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2806 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002807 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002808 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2809 TrueIfSigned = true;
2810 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002811 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2812 TrueIfSigned = true;
2813 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002814 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2815 TrueIfSigned = false;
2816 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002817 case ICmpInst::ICMP_UGT:
2818 // True if LHS u> RHS and RHS == high-bit-mask - 1
2819 TrueIfSigned = true;
2820 return RHS->getValue() ==
2821 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2822 case ICmpInst::ICMP_UGE:
2823 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2824 TrueIfSigned = true;
2825 return RHS->getValue() ==
2826 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002827 default:
2828 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002829 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002830}
2831
Chris Lattner7e708292002-06-25 16:13:24 +00002832Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002833 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002834 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002835
Chris Lattnere87597f2004-10-16 18:11:37 +00002836 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2837 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2838
Chris Lattner233f7dc2002-08-12 21:17:25 +00002839 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002840 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2841 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002842
2843 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002844 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002845 if (SI->getOpcode() == Instruction::Shl)
2846 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002847 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002848 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002849
Zhou Sheng843f07672007-04-19 05:39:12 +00002850 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002851 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2852 if (CI->equalsInt(1)) // X * 1 == X
2853 return ReplaceInstUsesWith(I, Op0);
2854 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002855 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002856
Zhou Sheng97b52c22007-03-29 01:57:21 +00002857 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002858 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002859 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002860 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002861 }
Robert Bocchino71698282004-07-27 21:02:21 +00002862 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002863 if (Op1F->isNullValue())
2864 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002865
Chris Lattnera2881962003-02-18 19:28:33 +00002866 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2867 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002868 // We need a better interface for long double here.
2869 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2870 if (Op1F->isExactlyValue(1.0))
2871 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002872 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002873
2874 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2875 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002876 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002877 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002878 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002879 Op1, "tmp");
2880 InsertNewInstBefore(Add, I);
2881 Value *C1C2 = ConstantExpr::getMul(Op1,
2882 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002883 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002884
2885 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002886
2887 // Try to fold constant mul into select arguments.
2888 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002889 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002890 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002891
2892 if (isa<PHINode>(Op0))
2893 if (Instruction *NV = FoldOpIntoPhi(I))
2894 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002895 }
2896
Chris Lattnera4f445b2003-03-10 23:23:04 +00002897 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2898 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002899 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002900
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002901 // If one of the operands of the multiply is a cast from a boolean value, then
2902 // we know the bool is either zero or one, so this is a 'masking' multiply.
2903 // See if we can simplify things based on how the boolean was originally
2904 // formed.
2905 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002906 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002907 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002908 BoolCast = CI;
2909 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002910 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002911 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002912 BoolCast = CI;
2913 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002914 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002915 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2916 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002917 bool TIS = false;
2918
Reid Spencere4d87aa2006-12-23 06:05:41 +00002919 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002920 // multiply into a shift/and combination.
2921 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002922 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2923 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002924 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002925 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002926 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002927 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002928 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002929 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002930 BoolCast->getOperand(0)->getName()+
2931 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002932
2933 // If the multiply type is not the same as the source type, sign extend
2934 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002935 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002936 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2937 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002938 Instruction::CastOps opcode =
2939 (SrcBits == DstBits ? Instruction::BitCast :
2940 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2941 V = InsertCastBefore(opcode, V, I.getType(), I);
2942 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002943
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002944 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002945 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002946 }
2947 }
2948 }
2949
Chris Lattner7e708292002-06-25 16:13:24 +00002950 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002951}
2952
Reid Spencer1628cec2006-10-26 06:15:43 +00002953/// This function implements the transforms on div instructions that work
2954/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2955/// used by the visitors to those instructions.
2956/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002957Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002958 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002959
Chris Lattner50b2ca42008-02-19 06:12:18 +00002960 // undef / X -> 0 for integer.
2961 // undef / X -> undef for FP (the undef could be a snan).
2962 if (isa<UndefValue>(Op0)) {
2963 if (Op0->getType()->isFPOrFPVector())
2964 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002965 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002966 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002967
2968 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002969 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002970 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002971
Chris Lattner25feae52008-01-28 00:58:18 +00002972 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2973 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002974 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002975 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2976 // the same basic block, then we replace the select with Y, and the
2977 // condition of the select with false (if the cond value is in the same BB).
2978 // If the select has uses other than the div, this allows them to be
2979 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2980 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002981 if (ST->isNullValue()) {
2982 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2983 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002984 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002985 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2986 I.setOperand(1, SI->getOperand(2));
2987 else
2988 UpdateValueUsesWith(SI, SI->getOperand(2));
2989 return &I;
2990 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002991
Chris Lattner25feae52008-01-28 00:58:18 +00002992 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2993 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002994 if (ST->isNullValue()) {
2995 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2996 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002997 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002998 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2999 I.setOperand(1, SI->getOperand(1));
3000 else
3001 UpdateValueUsesWith(SI, SI->getOperand(1));
3002 return &I;
3003 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003004 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003005
Reid Spencer1628cec2006-10-26 06:15:43 +00003006 return 0;
3007}
Misha Brukmanfd939082005-04-21 23:48:37 +00003008
Reid Spencer1628cec2006-10-26 06:15:43 +00003009/// This function implements the transforms common to both integer division
3010/// instructions (udiv and sdiv). It is called by the visitors to those integer
3011/// division instructions.
3012/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003013Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003014 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3015
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003016 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3017 if (Op0 == Op1)
3018 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
3019
Reid Spencer1628cec2006-10-26 06:15:43 +00003020 if (Instruction *Common = commonDivTransforms(I))
3021 return Common;
3022
3023 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3024 // div X, 1 == X
3025 if (RHS->equalsInt(1))
3026 return ReplaceInstUsesWith(I, Op0);
3027
3028 // (X / C1) / C2 -> X / (C1*C2)
3029 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3030 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3031 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003032 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3033 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3034 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003035 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003036 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003037 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003038
Reid Spencerbca0e382007-03-23 20:05:17 +00003039 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003040 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3041 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3042 return R;
3043 if (isa<PHINode>(Op0))
3044 if (Instruction *NV = FoldOpIntoPhi(I))
3045 return NV;
3046 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003047 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003048
Chris Lattnera2881962003-02-18 19:28:33 +00003049 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003050 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003051 if (LHS->equalsInt(0))
3052 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3053
Reid Spencer1628cec2006-10-26 06:15:43 +00003054 return 0;
3055}
3056
3057Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3058 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3059
3060 // Handle the integer div common cases
3061 if (Instruction *Common = commonIDivTransforms(I))
3062 return Common;
3063
3064 // X udiv C^2 -> X >> C
3065 // Check to see if this is an unsigned division with an exact power of 2,
3066 // if so, convert to a right shift.
3067 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003068 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003069 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003070 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003071 }
3072
3073 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003074 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003075 if (RHSI->getOpcode() == Instruction::Shl &&
3076 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003077 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003078 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003079 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003080 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003081 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003082 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003083 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003084 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003085 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003086 }
3087 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003088 }
3089
Reid Spencer1628cec2006-10-26 06:15:43 +00003090 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3091 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003092 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003093 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003094 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003095 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003096 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003097 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003098 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003099 // Construct the "on true" case of the select
3100 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003101 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003102 Op0, TC, SI->getName()+".t");
3103 TSI = InsertNewInstBefore(TSI, I);
3104
3105 // Construct the "on false" case of the select
3106 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003107 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003108 Op0, FC, SI->getName()+".f");
3109 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003110
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003111 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003112 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003113 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003114 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003115 return 0;
3116}
3117
Reid Spencer1628cec2006-10-26 06:15:43 +00003118Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3119 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3120
3121 // Handle the integer div common cases
3122 if (Instruction *Common = commonIDivTransforms(I))
3123 return Common;
3124
3125 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3126 // sdiv X, -1 == -X
3127 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003128 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003129
3130 // -X/C -> X/-C
3131 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003132 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003133 }
3134
3135 // If the sign bits of both operands are zero (i.e. we can prove they are
3136 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003137 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003138 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003139 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003140 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003141 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003142 }
3143 }
3144
3145 return 0;
3146}
3147
3148Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3149 return commonDivTransforms(I);
3150}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003151
Reid Spencer0a783f72006-11-02 01:53:59 +00003152/// This function implements the transforms on rem instructions that work
3153/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3154/// is used by the visitors to those instructions.
3155/// @brief Transforms common to all three rem instructions
3156Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003157 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003158
Chris Lattner50b2ca42008-02-19 06:12:18 +00003159 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003160 if (Constant *LHS = dyn_cast<Constant>(Op0))
3161 if (LHS->isNullValue())
3162 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3163
Chris Lattner50b2ca42008-02-19 06:12:18 +00003164 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3165 if (I.getType()->isFPOrFPVector())
3166 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003167 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003168 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003169 if (isa<UndefValue>(Op1))
3170 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003171
3172 // Handle cases involving: rem X, (select Cond, Y, Z)
3173 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3174 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3175 // the same basic block, then we replace the select with Y, and the
3176 // condition of the select with false (if the cond value is in the same
3177 // BB). If the select has uses other than the div, this allows them to be
3178 // simplified also.
3179 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3180 if (ST->isNullValue()) {
3181 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3182 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003183 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003184 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3185 I.setOperand(1, SI->getOperand(2));
3186 else
3187 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003188 return &I;
3189 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003190 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3191 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3192 if (ST->isNullValue()) {
3193 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3194 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003195 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003196 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3197 I.setOperand(1, SI->getOperand(1));
3198 else
3199 UpdateValueUsesWith(SI, SI->getOperand(1));
3200 return &I;
3201 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003202 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003203
Reid Spencer0a783f72006-11-02 01:53:59 +00003204 return 0;
3205}
3206
3207/// This function implements the transforms common to both integer remainder
3208/// instructions (urem and srem). It is called by the visitors to those integer
3209/// remainder instructions.
3210/// @brief Common integer remainder transforms
3211Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3212 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3213
3214 if (Instruction *common = commonRemTransforms(I))
3215 return common;
3216
Chris Lattner857e8cd2004-12-12 21:48:58 +00003217 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003218 // X % 0 == undef, we don't need to preserve faults!
3219 if (RHS->equalsInt(0))
3220 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3221
Chris Lattnera2881962003-02-18 19:28:33 +00003222 if (RHS->equalsInt(1)) // X % 1 == 0
3223 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3224
Chris Lattner97943922006-02-28 05:49:21 +00003225 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3226 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3227 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3228 return R;
3229 } else if (isa<PHINode>(Op0I)) {
3230 if (Instruction *NV = FoldOpIntoPhi(I))
3231 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003232 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003233
3234 // See if we can fold away this rem instruction.
3235 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3236 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3237 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3238 KnownZero, KnownOne))
3239 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003240 }
Chris Lattnera2881962003-02-18 19:28:33 +00003241 }
3242
Reid Spencer0a783f72006-11-02 01:53:59 +00003243 return 0;
3244}
3245
3246Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3247 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3248
3249 if (Instruction *common = commonIRemTransforms(I))
3250 return common;
3251
3252 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3253 // X urem C^2 -> X and C
3254 // Check to see if this is an unsigned remainder with an exact power of 2,
3255 // if so, convert to a bitwise and.
3256 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003257 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003258 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003259 }
3260
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003261 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003262 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3263 if (RHSI->getOpcode() == Instruction::Shl &&
3264 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003265 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003266 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003267 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003268 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003269 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003270 }
3271 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003272 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003273
Reid Spencer0a783f72006-11-02 01:53:59 +00003274 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3275 // where C1&C2 are powers of two.
3276 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3277 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3278 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3279 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003280 if ((STO->getValue().isPowerOf2()) &&
3281 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003282 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003283 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003284 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003285 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003286 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003287 }
3288 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003289 }
3290
Chris Lattner3f5b8772002-05-06 16:14:14 +00003291 return 0;
3292}
3293
Reid Spencer0a783f72006-11-02 01:53:59 +00003294Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3295 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3296
Dan Gohmancff55092007-11-05 23:16:33 +00003297 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003298 if (Instruction *common = commonIRemTransforms(I))
3299 return common;
3300
3301 if (Value *RHSNeg = dyn_castNegVal(Op1))
3302 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003303 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003304 // X % -Y -> X % Y
3305 AddUsesToWorkList(I);
3306 I.setOperand(1, RHSNeg);
3307 return &I;
3308 }
3309
Dan Gohmancff55092007-11-05 23:16:33 +00003310 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003311 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003312 if (I.getType()->isInteger()) {
3313 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3314 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3315 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003316 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003317 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003318 }
3319
3320 return 0;
3321}
3322
3323Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003324 return commonRemTransforms(I);
3325}
3326
Chris Lattner8b170942002-08-09 23:47:40 +00003327// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003328static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003329 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003330 if (!isSigned)
3331 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3332 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003333}
3334
3335// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003336static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003337 if (!isSigned)
3338 return C->getValue() == 1; // unsigned
3339
3340 // Calculate 1111111111000000000000
3341 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3342 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003343}
3344
Chris Lattner457dd822004-06-09 07:59:58 +00003345// isOneBitSet - Return true if there is exactly one bit set in the specified
3346// constant.
3347static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003348 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003349}
3350
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003351// isHighOnes - Return true if the constant is of the form 1+0+.
3352// This is the same as lowones(~X).
3353static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003354 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003355}
3356
Reid Spencere4d87aa2006-12-23 06:05:41 +00003357/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003358/// are carefully arranged to allow folding of expressions such as:
3359///
3360/// (A < B) | (A > B) --> (A != B)
3361///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003362/// Note that this is only valid if the first and second predicates have the
3363/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003364///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003365/// Three bits are used to represent the condition, as follows:
3366/// 0 A > B
3367/// 1 A == B
3368/// 2 A < B
3369///
3370/// <=> Value Definition
3371/// 000 0 Always false
3372/// 001 1 A > B
3373/// 010 2 A == B
3374/// 011 3 A >= B
3375/// 100 4 A < B
3376/// 101 5 A != B
3377/// 110 6 A <= B
3378/// 111 7 Always true
3379///
3380static unsigned getICmpCode(const ICmpInst *ICI) {
3381 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003382 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003383 case ICmpInst::ICMP_UGT: return 1; // 001
3384 case ICmpInst::ICMP_SGT: return 1; // 001
3385 case ICmpInst::ICMP_EQ: return 2; // 010
3386 case ICmpInst::ICMP_UGE: return 3; // 011
3387 case ICmpInst::ICMP_SGE: return 3; // 011
3388 case ICmpInst::ICMP_ULT: return 4; // 100
3389 case ICmpInst::ICMP_SLT: return 4; // 100
3390 case ICmpInst::ICMP_NE: return 5; // 101
3391 case ICmpInst::ICMP_ULE: return 6; // 110
3392 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003393 // True -> 7
3394 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003395 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003396 return 0;
3397 }
3398}
3399
Reid Spencere4d87aa2006-12-23 06:05:41 +00003400/// getICmpValue - This is the complement of getICmpCode, which turns an
3401/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003402/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003403/// of predicate to use in new icmp instructions.
3404static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3405 switch (code) {
3406 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003407 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003408 case 1:
3409 if (sign)
3410 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3411 else
3412 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3413 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3414 case 3:
3415 if (sign)
3416 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3417 else
3418 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3419 case 4:
3420 if (sign)
3421 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3422 else
3423 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3424 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3425 case 6:
3426 if (sign)
3427 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3428 else
3429 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003430 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003431 }
3432}
3433
Reid Spencere4d87aa2006-12-23 06:05:41 +00003434static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3435 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3436 (ICmpInst::isSignedPredicate(p1) &&
3437 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3438 (ICmpInst::isSignedPredicate(p2) &&
3439 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3440}
3441
3442namespace {
3443// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3444struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003445 InstCombiner &IC;
3446 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003447 ICmpInst::Predicate pred;
3448 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3449 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3450 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003451 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003452 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3453 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003454 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3455 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003456 return false;
3457 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003458 Instruction *apply(Instruction &Log) const {
3459 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3460 if (ICI->getOperand(0) != LHS) {
3461 assert(ICI->getOperand(1) == LHS);
3462 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003463 }
3464
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003465 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003466 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003467 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003468 unsigned Code;
3469 switch (Log.getOpcode()) {
3470 case Instruction::And: Code = LHSCode & RHSCode; break;
3471 case Instruction::Or: Code = LHSCode | RHSCode; break;
3472 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003473 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003474 }
3475
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003476 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3477 ICmpInst::isSignedPredicate(ICI->getPredicate());
3478
3479 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003480 if (Instruction *I = dyn_cast<Instruction>(RV))
3481 return I;
3482 // Otherwise, it's a constant boolean value...
3483 return IC.ReplaceInstUsesWith(Log, RV);
3484 }
3485};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003486} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003487
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003488// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3489// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003490// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003491Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003492 ConstantInt *OpRHS,
3493 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003494 BinaryOperator &TheAnd) {
3495 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003496 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003497 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003498 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003499
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003500 switch (Op->getOpcode()) {
3501 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003502 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003503 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003504 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003505 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003506 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003507 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003508 }
3509 break;
3510 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003511 if (Together == AndRHS) // (X | C) & C --> C
3512 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003513
Chris Lattner6e7ba452005-01-01 16:22:27 +00003514 if (Op->hasOneUse() && Together != OpRHS) {
3515 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003516 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003517 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003518 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003519 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003520 }
3521 break;
3522 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003523 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003524 // Adding a one to a single bit bit-field should be turned into an XOR
3525 // of the bit. First thing to check is to see if this AND is with a
3526 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003527 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003528
3529 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003530 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003531 // Ok, at this point, we know that we are masking the result of the
3532 // ADD down to exactly one bit. If the constant we are adding has
3533 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003534 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003535
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003536 // Check to see if any bits below the one bit set in AndRHSV are set.
3537 if ((AddRHS & (AndRHSV-1)) == 0) {
3538 // If not, the only thing that can effect the output of the AND is
3539 // the bit specified by AndRHSV. If that bit is set, the effect of
3540 // the XOR is to toggle the bit. If it is clear, then the ADD has
3541 // no effect.
3542 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3543 TheAnd.setOperand(0, X);
3544 return &TheAnd;
3545 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003547 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003548 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003549 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003550 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003551 }
3552 }
3553 }
3554 }
3555 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003556
3557 case Instruction::Shl: {
3558 // We know that the AND will not produce any of the bits shifted in, so if
3559 // the anded constant includes them, clear them now!
3560 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003561 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003562 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003563 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3564 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003565
Zhou Sheng290bec52007-03-29 08:15:12 +00003566 if (CI->getValue() == ShlMask) {
3567 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003568 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3569 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003570 TheAnd.setOperand(1, CI);
3571 return &TheAnd;
3572 }
3573 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003574 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003575 case Instruction::LShr:
3576 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003577 // We know that the AND will not produce any of the bits shifted in, so if
3578 // the anded constant includes them, clear them now! This only applies to
3579 // unsigned shifts, because a signed shr may bring in set bits!
3580 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003581 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003582 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003583 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3584 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003585
Zhou Sheng290bec52007-03-29 08:15:12 +00003586 if (CI->getValue() == ShrMask) {
3587 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003588 return ReplaceInstUsesWith(TheAnd, Op);
3589 } else if (CI != AndRHS) {
3590 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3591 return &TheAnd;
3592 }
3593 break;
3594 }
3595 case Instruction::AShr:
3596 // Signed shr.
3597 // See if this is shifting in some sign extension, then masking it out
3598 // with an and.
3599 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003600 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003601 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003602 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3603 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003604 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003605 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003606 // Make the argument unsigned.
3607 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003608 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003609 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003610 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003611 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003612 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003613 }
3614 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003615 }
3616 return 0;
3617}
3618
Chris Lattner8b170942002-08-09 23:47:40 +00003619
Chris Lattnera96879a2004-09-29 17:40:11 +00003620/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3621/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003622/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3623/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003624/// insert new instructions.
3625Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003626 bool isSigned, bool Inside,
3627 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003628 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003629 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003630 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003631
Chris Lattnera96879a2004-09-29 17:40:11 +00003632 if (Inside) {
3633 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003634 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003635
Reid Spencere4d87aa2006-12-23 06:05:41 +00003636 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003637 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003638 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3640 return new ICmpInst(pred, V, Hi);
3641 }
3642
3643 // Emit V-Lo <u Hi-Lo
3644 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003645 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003646 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003647 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3648 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003649 }
3650
3651 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003652 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003653
Reid Spencere4e40032007-03-21 23:19:50 +00003654 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003655 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003656 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003657 ICmpInst::Predicate pred = (isSigned ?
3658 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3659 return new ICmpInst(pred, V, Hi);
3660 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003661
Reid Spencere4e40032007-03-21 23:19:50 +00003662 // Emit V-Lo >u Hi-1-Lo
3663 // Note that Hi has already had one subtracted from it, above.
3664 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003665 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003666 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003667 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3668 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003669}
3670
Chris Lattner7203e152005-09-18 07:22:02 +00003671// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3672// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3673// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3674// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003675static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003676 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003677 uint32_t BitWidth = Val->getType()->getBitWidth();
3678 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003679
3680 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003681 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003682 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003683 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003684 return true;
3685}
3686
Chris Lattner7203e152005-09-18 07:22:02 +00003687/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3688/// where isSub determines whether the operator is a sub. If we can fold one of
3689/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003690///
3691/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3692/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3693/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3694///
3695/// return (A +/- B).
3696///
3697Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003698 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003699 Instruction &I) {
3700 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3701 if (!LHSI || LHSI->getNumOperands() != 2 ||
3702 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3703
3704 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3705
3706 switch (LHSI->getOpcode()) {
3707 default: return 0;
3708 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003709 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003710 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003711 if ((Mask->getValue().countLeadingZeros() +
3712 Mask->getValue().countPopulation()) ==
3713 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003714 break;
3715
3716 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3717 // part, we don't need any explicit masks to take them out of A. If that
3718 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003719 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003720 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003721 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003722 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003723 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003724 break;
3725 }
3726 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003727 return 0;
3728 case Instruction::Or:
3729 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003730 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003731 if ((Mask->getValue().countLeadingZeros() +
3732 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003733 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003734 break;
3735 return 0;
3736 }
3737
3738 Instruction *New;
3739 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003740 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003741 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003742 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003743 return InsertNewInstBefore(New, I);
3744}
3745
Chris Lattner7e708292002-06-25 16:13:24 +00003746Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003747 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003748 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003749
Chris Lattnere87597f2004-10-16 18:11:37 +00003750 if (isa<UndefValue>(Op1)) // X & undef -> 0
3751 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3752
Chris Lattner6e7ba452005-01-01 16:22:27 +00003753 // and X, X = X
3754 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003755 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003756
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003757 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003758 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003759 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003760 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3761 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3762 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003763 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003764 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003765 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003766 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003767 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003768 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003769 } else if (isa<ConstantAggregateZero>(Op1)) {
3770 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003771 }
3772 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003773
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003774 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003775 const APInt& AndRHSMask = AndRHS->getValue();
3776 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003777
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003778 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003779 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003780 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003781 Value *Op0LHS = Op0I->getOperand(0);
3782 Value *Op0RHS = Op0I->getOperand(1);
3783 switch (Op0I->getOpcode()) {
3784 case Instruction::Xor:
3785 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003786 // If the mask is only needed on one incoming arm, push it up.
3787 if (Op0I->hasOneUse()) {
3788 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3789 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003790 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003791 Op0RHS->getName()+".masked");
3792 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003793 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003794 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003795 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003796 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003797 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3798 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003799 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003800 Op0LHS->getName()+".masked");
3801 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003802 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003803 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3804 }
3805 }
3806
Chris Lattner6e7ba452005-01-01 16:22:27 +00003807 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003808 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003809 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3810 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3811 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3812 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003813 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003814 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003815 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003816 break;
3817
3818 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003819 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3820 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3821 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3822 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003823 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003824 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003825 }
3826
Chris Lattner58403262003-07-23 19:25:52 +00003827 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003828 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003829 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003830 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003831 // If this is an integer truncation or change from signed-to-unsigned, and
3832 // if the source is an and/or with immediate, transform it. This
3833 // frequently occurs for bitfield accesses.
3834 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003835 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003836 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003837 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003838 if (CastOp->getOpcode() == Instruction::And) {
3839 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003840 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3841 // This will fold the two constants together, which may allow
3842 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003843 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003844 CastOp->getOperand(0), I.getType(),
3845 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003846 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003847 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003848 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003849 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003850 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003851 } else if (CastOp->getOpcode() == Instruction::Or) {
3852 // Change: and (cast (or X, C1) to T), C2
3853 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003854 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003855 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3856 return ReplaceInstUsesWith(I, AndRHS);
3857 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003858 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003859 }
Chris Lattner06782f82003-07-23 19:36:21 +00003860 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003861
3862 // Try to fold constant and into select arguments.
3863 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003864 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003865 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003866 if (isa<PHINode>(Op0))
3867 if (Instruction *NV = FoldOpIntoPhi(I))
3868 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003869 }
3870
Chris Lattner8d969642003-03-10 23:06:50 +00003871 Value *Op0NotVal = dyn_castNotVal(Op0);
3872 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003873
Chris Lattner5b62aa72004-06-18 06:07:51 +00003874 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3875 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3876
Misha Brukmancb6267b2004-07-30 12:50:08 +00003877 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003878 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003879 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003880 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003881 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003882 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003883 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003884
3885 {
Chris Lattner003b6202007-06-15 05:58:24 +00003886 Value *A = 0, *B = 0, *C = 0, *D = 0;
3887 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003888 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3889 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003890
3891 // (A|B) & ~(A&B) -> A^B
3892 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3893 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003894 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003895 }
3896 }
3897
3898 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003899 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3900 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003901
3902 // ~(A&B) & (A|B) -> A^B
3903 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3904 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003905 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003906 }
3907 }
Chris Lattner64daab52006-04-01 08:03:55 +00003908
3909 if (Op0->hasOneUse() &&
3910 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3911 if (A == Op1) { // (A^B)&A -> A&(A^B)
3912 I.swapOperands(); // Simplify below
3913 std::swap(Op0, Op1);
3914 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3915 cast<BinaryOperator>(Op0)->swapOperands();
3916 I.swapOperands(); // Simplify below
3917 std::swap(Op0, Op1);
3918 }
3919 }
3920 if (Op1->hasOneUse() &&
3921 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3922 if (B == Op0) { // B&(A^B) -> B&(B^A)
3923 cast<BinaryOperator>(Op1)->swapOperands();
3924 std::swap(A, B);
3925 }
3926 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003927 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003928 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003929 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003930 }
3931 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003932 }
3933
Reid Spencere4d87aa2006-12-23 06:05:41 +00003934 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3935 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3936 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003937 return R;
3938
Chris Lattner955f3312004-09-28 21:48:02 +00003939 Value *LHSVal, *RHSVal;
3940 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003941 ICmpInst::Predicate LHSCC, RHSCC;
3942 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3943 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3944 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3945 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3946 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3947 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3948 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003949 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3950
3951 // Don't try to fold ICMP_SLT + ICMP_ULT.
3952 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3953 ICmpInst::isSignedPredicate(LHSCC) ==
3954 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003955 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003956 ICmpInst::Predicate GT;
3957 if (ICmpInst::isSignedPredicate(LHSCC) ||
3958 (ICmpInst::isEquality(LHSCC) &&
3959 ICmpInst::isSignedPredicate(RHSCC)))
3960 GT = ICmpInst::ICMP_SGT;
3961 else
3962 GT = ICmpInst::ICMP_UGT;
3963
Reid Spencere4d87aa2006-12-23 06:05:41 +00003964 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3965 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003966 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003967 std::swap(LHS, RHS);
3968 std::swap(LHSCst, RHSCst);
3969 std::swap(LHSCC, RHSCC);
3970 }
3971
Reid Spencere4d87aa2006-12-23 06:05:41 +00003972 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003973 // comparing a value against two constants and and'ing the result
3974 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003975 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3976 // (from the FoldICmpLogical check above), that the two constants
3977 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003978 assert(LHSCst != RHSCst && "Compares not folded above?");
3979
3980 switch (LHSCC) {
3981 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003982 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003983 switch (RHSCC) {
3984 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003985 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3986 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3987 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003988 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003989 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3990 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3991 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003992 return ReplaceInstUsesWith(I, LHS);
3993 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003994 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003995 switch (RHSCC) {
3996 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003997 case ICmpInst::ICMP_ULT:
3998 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3999 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4000 break; // (X != 13 & X u< 15) -> no change
4001 case ICmpInst::ICMP_SLT:
4002 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4003 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4004 break; // (X != 13 & X s< 15) -> no change
4005 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4006 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4007 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004008 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004009 case ICmpInst::ICMP_NE:
4010 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004011 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004012 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004013 LHSVal->getName()+".off");
4014 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004015 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4016 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004017 }
4018 break; // (X != 13 & X != 15) -> no change
4019 }
4020 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004021 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004022 switch (RHSCC) {
4023 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004024 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4025 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004026 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004027 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4028 break;
4029 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4030 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004031 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004032 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4033 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004034 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004035 break;
4036 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004037 switch (RHSCC) {
4038 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004039 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4040 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004041 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004042 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4043 break;
4044 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4045 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004046 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004047 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4048 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004049 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004050 break;
4051 case ICmpInst::ICMP_UGT:
4052 switch (RHSCC) {
4053 default: assert(0 && "Unknown integer condition code!");
4054 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4055 return ReplaceInstUsesWith(I, LHS);
4056 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4057 return ReplaceInstUsesWith(I, RHS);
4058 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4059 break;
4060 case ICmpInst::ICMP_NE:
4061 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4062 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4063 break; // (X u> 13 & X != 15) -> no change
4064 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4065 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4066 true, I);
4067 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4068 break;
4069 }
4070 break;
4071 case ICmpInst::ICMP_SGT:
4072 switch (RHSCC) {
4073 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004074 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004075 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4076 return ReplaceInstUsesWith(I, RHS);
4077 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4078 break;
4079 case ICmpInst::ICMP_NE:
4080 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4081 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4082 break; // (X s> 13 & X != 15) -> no change
4083 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4084 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4085 true, I);
4086 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4087 break;
4088 }
4089 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004090 }
4091 }
4092 }
4093
Chris Lattner6fc205f2006-05-05 06:39:07 +00004094 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004095 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4096 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4097 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4098 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004099 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004100 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004101 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4102 I.getType(), TD) &&
4103 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4104 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004105 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004106 Op1C->getOperand(0),
4107 I.getName());
4108 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004109 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004110 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004111 }
Chris Lattnere511b742006-11-14 07:46:50 +00004112
4113 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004114 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4115 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4116 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004117 SI0->getOperand(1) == SI1->getOperand(1) &&
4118 (SI0->hasOneUse() || SI1->hasOneUse())) {
4119 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004120 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004121 SI1->getOperand(0),
4122 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004123 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004124 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004125 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004126 }
4127
Chris Lattner99c65742007-10-24 05:38:08 +00004128 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4129 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4130 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4131 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4132 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4133 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4134 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4135 // If either of the constants are nans, then the whole thing returns
4136 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004137 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004138 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4139 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4140 RHS->getOperand(0));
4141 }
4142 }
4143 }
4144
Chris Lattner7e708292002-06-25 16:13:24 +00004145 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004146}
4147
Chris Lattnerafe91a52006-06-15 19:07:26 +00004148/// CollectBSwapParts - Look to see if the specified value defines a single byte
4149/// in the result. If it does, and if the specified byte hasn't been filled in
4150/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004151static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004152 Instruction *I = dyn_cast<Instruction>(V);
4153 if (I == 0) return true;
4154
4155 // If this is an or instruction, it is an inner node of the bswap.
4156 if (I->getOpcode() == Instruction::Or)
4157 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4158 CollectBSwapParts(I->getOperand(1), ByteValues);
4159
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004160 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004161 // If this is a shift by a constant int, and it is "24", then its operand
4162 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004163 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004164 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004165 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004166 8*(ByteValues.size()-1))
4167 return true;
4168
4169 unsigned DestNo;
4170 if (I->getOpcode() == Instruction::Shl) {
4171 // X << 24 defines the top byte with the lowest of the input bytes.
4172 DestNo = ByteValues.size()-1;
4173 } else {
4174 // X >>u 24 defines the low byte with the highest of the input bytes.
4175 DestNo = 0;
4176 }
4177
4178 // If the destination byte value is already defined, the values are or'd
4179 // together, which isn't a bswap (unless it's an or of the same bits).
4180 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4181 return true;
4182 ByteValues[DestNo] = I->getOperand(0);
4183 return false;
4184 }
4185
4186 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4187 // don't have this.
4188 Value *Shift = 0, *ShiftLHS = 0;
4189 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4190 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4191 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4192 return true;
4193 Instruction *SI = cast<Instruction>(Shift);
4194
4195 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004196 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4197 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004198 return true;
4199
4200 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4201 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004202 if (AndAmt->getValue().getActiveBits() > 64)
4203 return true;
4204 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004205 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004206 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004207 break;
4208 // Unknown mask for bswap.
4209 if (DestByte == ByteValues.size()) return true;
4210
Reid Spencerb83eb642006-10-20 07:07:24 +00004211 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004212 unsigned SrcByte;
4213 if (SI->getOpcode() == Instruction::Shl)
4214 SrcByte = DestByte - ShiftBytes;
4215 else
4216 SrcByte = DestByte + ShiftBytes;
4217
4218 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4219 if (SrcByte != ByteValues.size()-DestByte-1)
4220 return true;
4221
4222 // If the destination byte value is already defined, the values are or'd
4223 // together, which isn't a bswap (unless it's an or of the same bits).
4224 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4225 return true;
4226 ByteValues[DestByte] = SI->getOperand(0);
4227 return false;
4228}
4229
4230/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4231/// If so, insert the new bswap intrinsic and return it.
4232Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004233 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4234 if (!ITy || ITy->getBitWidth() % 16)
4235 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004236
4237 /// ByteValues - For each byte of the result, we keep track of which value
4238 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004239 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004240 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004241
4242 // Try to find all the pieces corresponding to the bswap.
4243 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4244 CollectBSwapParts(I.getOperand(1), ByteValues))
4245 return 0;
4246
4247 // Check to see if all of the bytes come from the same value.
4248 Value *V = ByteValues[0];
4249 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4250
4251 // Check to make sure that all of the bytes come from the same value.
4252 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4253 if (ByteValues[i] != V)
4254 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004255 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004256 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004257 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004258 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004259}
4260
4261
Chris Lattner7e708292002-06-25 16:13:24 +00004262Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004263 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004264 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004265
Chris Lattner42593e62007-03-24 23:56:43 +00004266 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004267 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004268
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004269 // or X, X = X
4270 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004271 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004272
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004273 // See if we can simplify any instructions used by the instruction whose sole
4274 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004275 if (!isa<VectorType>(I.getType())) {
4276 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4277 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4278 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4279 KnownZero, KnownOne))
4280 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004281 } else if (isa<ConstantAggregateZero>(Op1)) {
4282 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4283 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4284 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4285 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004286 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004287
4288
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004289
Chris Lattner3f5b8772002-05-06 16:14:14 +00004290 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004291 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004292 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004293 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4294 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004295 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004296 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004297 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004298 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004299 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004300 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004301
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004302 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4303 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004304 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004305 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004306 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004307 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004308 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004309 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004310
4311 // Try to fold constant and into select arguments.
4312 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004313 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004314 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004315 if (isa<PHINode>(Op0))
4316 if (Instruction *NV = FoldOpIntoPhi(I))
4317 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004318 }
4319
Chris Lattner4f637d42006-01-06 17:59:59 +00004320 Value *A = 0, *B = 0;
4321 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004322
4323 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4324 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4325 return ReplaceInstUsesWith(I, Op1);
4326 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4327 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4328 return ReplaceInstUsesWith(I, Op0);
4329
Chris Lattner6423d4c2006-07-10 20:25:24 +00004330 // (A | B) | C and A | (B | C) -> bswap if possible.
4331 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004332 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004333 match(Op1, m_Or(m_Value(), m_Value())) ||
4334 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4335 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004336 if (Instruction *BSwap = MatchBSwap(I))
4337 return BSwap;
4338 }
4339
Chris Lattner6e4c6492005-05-09 04:58:36 +00004340 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4341 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004342 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004343 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004344 InsertNewInstBefore(NOr, I);
4345 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004346 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004347 }
4348
4349 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4350 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004351 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004352 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004353 InsertNewInstBefore(NOr, I);
4354 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004355 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004356 }
4357
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004358 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004359 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004360 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4361 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004362 Value *V1 = 0, *V2 = 0, *V3 = 0;
4363 C1 = dyn_cast<ConstantInt>(C);
4364 C2 = dyn_cast<ConstantInt>(D);
4365 if (C1 && C2) { // (A & C1)|(B & C2)
4366 // If we have: ((V + N) & C1) | (V & C2)
4367 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4368 // replace with V+N.
4369 if (C1->getValue() == ~C2->getValue()) {
4370 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4371 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4372 // Add commutes, try both ways.
4373 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4374 return ReplaceInstUsesWith(I, A);
4375 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4376 return ReplaceInstUsesWith(I, A);
4377 }
4378 // Or commutes, try both ways.
4379 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4380 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4381 // Add commutes, try both ways.
4382 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4383 return ReplaceInstUsesWith(I, B);
4384 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4385 return ReplaceInstUsesWith(I, B);
4386 }
4387 }
Chris Lattner044e5332007-04-08 08:01:49 +00004388 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004389 }
4390
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004391 // Check to see if we have any common things being and'ed. If so, find the
4392 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004393 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4394 if (A == B) // (A & C)|(A & D) == A & (C|D)
4395 V1 = A, V2 = C, V3 = D;
4396 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4397 V1 = A, V2 = B, V3 = C;
4398 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4399 V1 = C, V2 = A, V3 = D;
4400 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4401 V1 = C, V2 = A, V3 = B;
4402
4403 if (V1) {
4404 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004405 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4406 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004407 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004408 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004409 }
Chris Lattnere511b742006-11-14 07:46:50 +00004410
4411 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004412 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4413 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4414 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004415 SI0->getOperand(1) == SI1->getOperand(1) &&
4416 (SI0->hasOneUse() || SI1->hasOneUse())) {
4417 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004418 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004419 SI1->getOperand(0),
4420 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004421 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004422 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004423 }
4424 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004425
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004426 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4427 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004428 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004429 } else {
4430 A = 0;
4431 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004432 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004433 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4434 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004435 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004436
Misha Brukmancb6267b2004-07-30 12:50:08 +00004437 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004438 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004439 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004440 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004441 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004442 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004443 }
Chris Lattnera2881962003-02-18 19:28:33 +00004444
Reid Spencere4d87aa2006-12-23 06:05:41 +00004445 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4446 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4447 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004448 return R;
4449
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004450 Value *LHSVal, *RHSVal;
4451 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004452 ICmpInst::Predicate LHSCC, RHSCC;
4453 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4454 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4455 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4456 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4457 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4458 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4459 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004460 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4461 // We can't fold (ugt x, C) | (sgt x, C2).
4462 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004463 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004464 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004465 bool NeedsSwap;
4466 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004467 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004468 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004469 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004470
4471 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004472 std::swap(LHS, RHS);
4473 std::swap(LHSCst, RHSCst);
4474 std::swap(LHSCC, RHSCC);
4475 }
4476
Reid Spencere4d87aa2006-12-23 06:05:41 +00004477 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004478 // comparing a value against two constants and or'ing the result
4479 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004480 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4481 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004482 // equal.
4483 assert(LHSCst != RHSCst && "Compares not folded above?");
4484
4485 switch (LHSCC) {
4486 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004487 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004488 switch (RHSCC) {
4489 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004490 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004491 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4492 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004493 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004494 LHSVal->getName()+".off");
4495 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004496 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004497 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004498 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004499 break; // (X == 13 | X == 15) -> no change
4500 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4501 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004502 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004503 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4504 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4505 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004506 return ReplaceInstUsesWith(I, RHS);
4507 }
4508 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004509 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004510 switch (RHSCC) {
4511 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004512 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4513 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4514 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004515 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004516 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4517 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4518 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004519 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004520 }
4521 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004522 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004523 switch (RHSCC) {
4524 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004525 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004526 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004527 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004528 // If RHSCst is [us]MAXINT, it is always false. Not handling
4529 // this can cause overflow.
4530 if (RHSCst->isMaxValue(false))
4531 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004532 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4533 false, I);
4534 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4535 break;
4536 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4537 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004538 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004539 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4540 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004541 }
4542 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004543 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004544 switch (RHSCC) {
4545 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004546 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4547 break;
4548 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004549 // If RHSCst is [us]MAXINT, it is always false. Not handling
4550 // this can cause overflow.
4551 if (RHSCst->isMaxValue(true))
4552 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004553 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4554 false, I);
4555 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4556 break;
4557 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4558 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4559 return ReplaceInstUsesWith(I, RHS);
4560 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4561 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004562 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004563 break;
4564 case ICmpInst::ICMP_UGT:
4565 switch (RHSCC) {
4566 default: assert(0 && "Unknown integer condition code!");
4567 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4568 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4569 return ReplaceInstUsesWith(I, LHS);
4570 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4571 break;
4572 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4573 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004574 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004575 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4576 break;
4577 }
4578 break;
4579 case ICmpInst::ICMP_SGT:
4580 switch (RHSCC) {
4581 default: assert(0 && "Unknown integer condition code!");
4582 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4583 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4584 return ReplaceInstUsesWith(I, LHS);
4585 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4586 break;
4587 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4588 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004589 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004590 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4591 break;
4592 }
4593 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004594 }
4595 }
4596 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004597
4598 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004599 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004600 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004601 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004602 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4603 !isa<ICmpInst>(Op1C->getOperand(0))) {
4604 const Type *SrcTy = Op0C->getOperand(0)->getType();
4605 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4606 // Only do this if the casts both really cause code to be
4607 // generated.
4608 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4609 I.getType(), TD) &&
4610 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4611 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004612 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004613 Op1C->getOperand(0),
4614 I.getName());
4615 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004616 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004617 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004618 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004619 }
Chris Lattner99c65742007-10-24 05:38:08 +00004620 }
4621
4622
4623 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4624 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4625 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4626 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004627 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4628 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004629 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4630 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4631 // If either of the constants are nans, then the whole thing returns
4632 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004633 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004634 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4635
4636 // Otherwise, no need to compare the two constants, compare the
4637 // rest.
4638 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4639 RHS->getOperand(0));
4640 }
4641 }
4642 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004643
Chris Lattner7e708292002-06-25 16:13:24 +00004644 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004645}
4646
Dan Gohman844731a2008-05-13 00:00:25 +00004647namespace {
4648
Chris Lattnerc317d392004-02-16 01:20:27 +00004649// XorSelf - Implements: X ^ X --> 0
4650struct XorSelf {
4651 Value *RHS;
4652 XorSelf(Value *rhs) : RHS(rhs) {}
4653 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4654 Instruction *apply(BinaryOperator &Xor) const {
4655 return &Xor;
4656 }
4657};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004658
Dan Gohman844731a2008-05-13 00:00:25 +00004659}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004660
Chris Lattner7e708292002-06-25 16:13:24 +00004661Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004662 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004663 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004664
Evan Chengd34af782008-03-25 20:07:13 +00004665 if (isa<UndefValue>(Op1)) {
4666 if (isa<UndefValue>(Op0))
4667 // Handle undef ^ undef -> 0 special case. This is a common
4668 // idiom (misuse).
4669 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004670 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004671 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004672
Chris Lattnerc317d392004-02-16 01:20:27 +00004673 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4674 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004675 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004676 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004677 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004678
4679 // See if we can simplify any instructions used by the instruction whose sole
4680 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004681 if (!isa<VectorType>(I.getType())) {
4682 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4683 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4684 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4685 KnownZero, KnownOne))
4686 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004687 } else if (isa<ConstantAggregateZero>(Op1)) {
4688 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004689 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004690
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004691 // Is this a ~ operation?
4692 if (Value *NotOp = dyn_castNotVal(&I)) {
4693 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4694 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4695 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4696 if (Op0I->getOpcode() == Instruction::And ||
4697 Op0I->getOpcode() == Instruction::Or) {
4698 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4699 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4700 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004701 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004702 Op0I->getOperand(1)->getName()+".not");
4703 InsertNewInstBefore(NotY, I);
4704 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004705 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004706 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004707 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004708 }
4709 }
4710 }
4711 }
4712
4713
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004714 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004715 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4716 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4717 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004718 return new ICmpInst(ICI->getInversePredicate(),
4719 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004720
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004721 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4722 return new FCmpInst(FCI->getInversePredicate(),
4723 FCI->getOperand(0), FCI->getOperand(1));
4724 }
4725
Reid Spencere4d87aa2006-12-23 06:05:41 +00004726 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004727 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004728 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4729 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004730 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4731 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004732 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004733 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004734 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004735
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004736 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004737 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004738 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004739 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004740 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004741 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004742 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004743 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004744 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004745 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004746 // (X + C) ^ signbit -> (X + C + signbit)
4747 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004748 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004749
Chris Lattner7c4049c2004-01-12 19:35:11 +00004750 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004751 } else if (Op0I->getOpcode() == Instruction::Or) {
4752 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004753 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004754 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4755 // Anything in both C1 and C2 is known to be zero, remove it from
4756 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004757 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004758 NewRHS = ConstantExpr::getAnd(NewRHS,
4759 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004760 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004761 I.setOperand(0, Op0I->getOperand(0));
4762 I.setOperand(1, NewRHS);
4763 return &I;
4764 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004765 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004766 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004767 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004768
4769 // Try to fold constant and into select arguments.
4770 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004771 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004772 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004773 if (isa<PHINode>(Op0))
4774 if (Instruction *NV = FoldOpIntoPhi(I))
4775 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004776 }
4777
Chris Lattner8d969642003-03-10 23:06:50 +00004778 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004779 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004780 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004781
Chris Lattner8d969642003-03-10 23:06:50 +00004782 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004783 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004784 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004785
Chris Lattner318bf792007-03-18 22:51:34 +00004786
4787 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4788 if (Op1I) {
4789 Value *A, *B;
4790 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4791 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004792 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004793 I.swapOperands();
4794 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004795 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004796 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004797 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004798 }
Chris Lattner318bf792007-03-18 22:51:34 +00004799 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4800 if (Op0 == A) // A^(A^B) == B
4801 return ReplaceInstUsesWith(I, B);
4802 else if (Op0 == B) // A^(B^A) == B
4803 return ReplaceInstUsesWith(I, A);
4804 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004805 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004806 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004807 std::swap(A, B);
4808 }
Chris Lattner318bf792007-03-18 22:51:34 +00004809 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004810 I.swapOperands(); // Simplified below.
4811 std::swap(Op0, Op1);
4812 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004813 }
Chris Lattner318bf792007-03-18 22:51:34 +00004814 }
4815
4816 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4817 if (Op0I) {
4818 Value *A, *B;
4819 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4820 if (A == Op1) // (B|A)^B == (A|B)^B
4821 std::swap(A, B);
4822 if (B == Op1) { // (A|B)^B == A & ~B
4823 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004824 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4825 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004826 }
Chris Lattner318bf792007-03-18 22:51:34 +00004827 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4828 if (Op1 == A) // (A^B)^A == B
4829 return ReplaceInstUsesWith(I, B);
4830 else if (Op1 == B) // (B^A)^A == B
4831 return ReplaceInstUsesWith(I, A);
4832 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4833 if (A == Op1) // (A&B)^A -> (B&A)^A
4834 std::swap(A, B);
4835 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004836 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004837 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004838 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4839 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004840 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004841 }
Chris Lattner318bf792007-03-18 22:51:34 +00004842 }
4843
4844 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4845 if (Op0I && Op1I && Op0I->isShift() &&
4846 Op0I->getOpcode() == Op1I->getOpcode() &&
4847 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4848 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4849 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004850 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004851 Op1I->getOperand(0),
4852 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004853 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004854 Op1I->getOperand(1));
4855 }
4856
4857 if (Op0I && Op1I) {
4858 Value *A, *B, *C, *D;
4859 // (A & B)^(A | B) -> A ^ B
4860 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4861 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4862 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004863 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004864 }
4865 // (A | B)^(A & B) -> A ^ B
4866 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4867 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4868 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004869 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004870 }
4871
4872 // (A & B)^(C & D)
4873 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4874 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4875 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4876 // (X & Y)^(X & Y) -> (Y^Z) & X
4877 Value *X = 0, *Y = 0, *Z = 0;
4878 if (A == C)
4879 X = A, Y = B, Z = D;
4880 else if (A == D)
4881 X = A, Y = B, Z = C;
4882 else if (B == C)
4883 X = B, Y = A, Z = D;
4884 else if (B == D)
4885 X = B, Y = A, Z = C;
4886
4887 if (X) {
4888 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004889 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4890 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004891 }
4892 }
4893 }
4894
Reid Spencere4d87aa2006-12-23 06:05:41 +00004895 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4896 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4897 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004898 return R;
4899
Chris Lattner6fc205f2006-05-05 06:39:07 +00004900 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004901 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004902 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004903 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4904 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004905 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004906 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004907 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4908 I.getType(), TD) &&
4909 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4910 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004911 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004912 Op1C->getOperand(0),
4913 I.getName());
4914 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004915 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004916 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004917 }
Chris Lattner99c65742007-10-24 05:38:08 +00004918 }
Chris Lattner7e708292002-06-25 16:13:24 +00004919 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004920}
4921
Chris Lattnera96879a2004-09-29 17:40:11 +00004922/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4923/// overflowed for this type.
4924static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004925 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004926 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004927
Reid Spencere4e40032007-03-21 23:19:50 +00004928 if (IsSigned)
4929 if (In2->getValue().isNegative())
4930 return Result->getValue().sgt(In1->getValue());
4931 else
4932 return Result->getValue().slt(In1->getValue());
4933 else
4934 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004935}
4936
Chris Lattner574da9b2005-01-13 20:14:25 +00004937/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4938/// code necessary to compute the offset from the base pointer (without adding
4939/// in the base pointer). Return the result as a signed integer of intptr size.
4940static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4941 TargetData &TD = IC.getTargetData();
4942 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004943 const Type *IntPtrTy = TD.getIntPtrType();
4944 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004945
4946 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004947 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004948 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004949
Chris Lattner574da9b2005-01-13 20:14:25 +00004950 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4951 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004952 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004953 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4954 if (OpC->isZero()) continue;
4955
4956 // Handle a struct index, which adds its field offset to the pointer.
4957 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4958 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4959
4960 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4961 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004962 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004963 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004964 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004965 ConstantInt::get(IntPtrTy, Size),
4966 GEP->getName()+".offs"), I);
4967 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004968 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004969
4970 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4971 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4972 Scale = ConstantExpr::getMul(OC, Scale);
4973 if (Constant *RC = dyn_cast<Constant>(Result))
4974 Result = ConstantExpr::getAdd(RC, Scale);
4975 else {
4976 // Emit an add instruction.
4977 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004978 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004979 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004980 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004981 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004982 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004983 // Convert to correct type.
4984 if (Op->getType() != IntPtrTy) {
4985 if (Constant *OpC = dyn_cast<Constant>(Op))
4986 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4987 else
4988 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4989 Op->getName()+".c"), I);
4990 }
4991 if (Size != 1) {
4992 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4993 if (Constant *OpC = dyn_cast<Constant>(Op))
4994 Op = ConstantExpr::getMul(OpC, Scale);
4995 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004996 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004997 GEP->getName()+".idx"), I);
4998 }
4999
5000 // Emit an add instruction.
5001 if (isa<Constant>(Op) && isa<Constant>(Result))
5002 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5003 cast<Constant>(Result));
5004 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005005 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005006 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005007 }
5008 return Result;
5009}
5010
Chris Lattner10c0d912008-04-22 02:53:33 +00005011
5012/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5013/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5014/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5015/// complex, and scales are involved. The above expression would also be legal
5016/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5017/// later form is less amenable to optimization though, and we are allowed to
5018/// generate the first by knowing that pointer arithmetic doesn't overflow.
5019///
5020/// If we can't emit an optimized form for this expression, this returns null.
5021///
5022static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5023 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005024 TargetData &TD = IC.getTargetData();
5025 gep_type_iterator GTI = gep_type_begin(GEP);
5026
5027 // Check to see if this gep only has a single variable index. If so, and if
5028 // any constant indices are a multiple of its scale, then we can compute this
5029 // in terms of the scale of the variable index. For example, if the GEP
5030 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5031 // because the expression will cross zero at the same point.
5032 unsigned i, e = GEP->getNumOperands();
5033 int64_t Offset = 0;
5034 for (i = 1; i != e; ++i, ++GTI) {
5035 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5036 // Compute the aggregate offset of constant indices.
5037 if (CI->isZero()) continue;
5038
5039 // Handle a struct index, which adds its field offset to the pointer.
5040 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5041 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5042 } else {
5043 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5044 Offset += Size*CI->getSExtValue();
5045 }
5046 } else {
5047 // Found our variable index.
5048 break;
5049 }
5050 }
5051
5052 // If there are no variable indices, we must have a constant offset, just
5053 // evaluate it the general way.
5054 if (i == e) return 0;
5055
5056 Value *VariableIdx = GEP->getOperand(i);
5057 // Determine the scale factor of the variable element. For example, this is
5058 // 4 if the variable index is into an array of i32.
5059 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5060
5061 // Verify that there are no other variable indices. If so, emit the hard way.
5062 for (++i, ++GTI; i != e; ++i, ++GTI) {
5063 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5064 if (!CI) return 0;
5065
5066 // Compute the aggregate offset of constant indices.
5067 if (CI->isZero()) continue;
5068
5069 // Handle a struct index, which adds its field offset to the pointer.
5070 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5071 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5072 } else {
5073 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5074 Offset += Size*CI->getSExtValue();
5075 }
5076 }
5077
5078 // Okay, we know we have a single variable index, which must be a
5079 // pointer/array/vector index. If there is no offset, life is simple, return
5080 // the index.
5081 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5082 if (Offset == 0) {
5083 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5084 // we don't need to bother extending: the extension won't affect where the
5085 // computation crosses zero.
5086 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5087 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5088 VariableIdx->getNameStart(), &I);
5089 return VariableIdx;
5090 }
5091
5092 // Otherwise, there is an index. The computation we will do will be modulo
5093 // the pointer size, so get it.
5094 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5095
5096 Offset &= PtrSizeMask;
5097 VariableScale &= PtrSizeMask;
5098
5099 // To do this transformation, any constant index must be a multiple of the
5100 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5101 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5102 // multiple of the variable scale.
5103 int64_t NewOffs = Offset / (int64_t)VariableScale;
5104 if (Offset != NewOffs*(int64_t)VariableScale)
5105 return 0;
5106
5107 // Okay, we can do this evaluation. Start by converting the index to intptr.
5108 const Type *IntPtrTy = TD.getIntPtrType();
5109 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005110 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005111 true /*SExt*/,
5112 VariableIdx->getNameStart(), &I);
5113 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005114 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005115}
5116
5117
Reid Spencere4d87aa2006-12-23 06:05:41 +00005118/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005119/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005120Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5121 ICmpInst::Predicate Cond,
5122 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005123 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005124
Chris Lattner10c0d912008-04-22 02:53:33 +00005125 // Look through bitcasts.
5126 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5127 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005128
Chris Lattner574da9b2005-01-13 20:14:25 +00005129 Value *PtrBase = GEPLHS->getOperand(0);
5130 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005131 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005132 // This transformation (ignoring the base and scales) is valid because we
5133 // know pointers can't overflow. See if we can output an optimized form.
5134 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5135
5136 // If not, synthesize the offset the hard way.
5137 if (Offset == 0)
5138 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005139 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5140 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005141 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005142 // If the base pointers are different, but the indices are the same, just
5143 // compare the base pointer.
5144 if (PtrBase != GEPRHS->getOperand(0)) {
5145 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005146 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005147 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005148 if (IndicesTheSame)
5149 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5150 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5151 IndicesTheSame = false;
5152 break;
5153 }
5154
5155 // If all indices are the same, just compare the base pointers.
5156 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005157 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5158 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005159
5160 // Otherwise, the base pointers are different and the indices are
5161 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005162 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005163 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005164
Chris Lattnere9d782b2005-01-13 22:25:21 +00005165 // If one of the GEPs has all zero indices, recurse.
5166 bool AllZeros = true;
5167 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5168 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5169 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5170 AllZeros = false;
5171 break;
5172 }
5173 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005174 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5175 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005176
5177 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005178 AllZeros = true;
5179 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5180 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5181 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5182 AllZeros = false;
5183 break;
5184 }
5185 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005186 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005187
Chris Lattner4401c9c2005-01-14 00:20:05 +00005188 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5189 // If the GEPs only differ by one index, compare it.
5190 unsigned NumDifferences = 0; // Keep track of # differences.
5191 unsigned DiffOperand = 0; // The operand that differs.
5192 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5193 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005194 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5195 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005196 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005197 NumDifferences = 2;
5198 break;
5199 } else {
5200 if (NumDifferences++) break;
5201 DiffOperand = i;
5202 }
5203 }
5204
5205 if (NumDifferences == 0) // SAME GEP?
5206 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005207 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005208 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005209
Chris Lattner4401c9c2005-01-14 00:20:05 +00005210 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005211 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5212 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005213 // Make sure we do a signed comparison here.
5214 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005215 }
5216 }
5217
Reid Spencere4d87aa2006-12-23 06:05:41 +00005218 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005219 // the result to fold to a constant!
5220 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5221 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5222 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5223 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5224 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005225 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005226 }
5227 }
5228 return 0;
5229}
5230
Reid Spencere4d87aa2006-12-23 06:05:41 +00005231Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5232 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005233 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005234
Chris Lattner58e97462007-01-14 19:42:17 +00005235 // Fold trivial predicates.
5236 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5237 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5238 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5239 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5240
5241 // Simplify 'fcmp pred X, X'
5242 if (Op0 == Op1) {
5243 switch (I.getPredicate()) {
5244 default: assert(0 && "Unknown predicate!");
5245 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5246 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5247 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5248 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5249 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5250 case FCmpInst::FCMP_OLT: // True if ordered and less than
5251 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5252 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5253
5254 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5255 case FCmpInst::FCMP_ULT: // True if unordered or less than
5256 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5257 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5258 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5259 I.setPredicate(FCmpInst::FCMP_UNO);
5260 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5261 return &I;
5262
5263 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5264 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5265 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5266 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5267 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5268 I.setPredicate(FCmpInst::FCMP_ORD);
5269 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5270 return &I;
5271 }
5272 }
5273
Reid Spencere4d87aa2006-12-23 06:05:41 +00005274 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005275 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005276
Reid Spencere4d87aa2006-12-23 06:05:41 +00005277 // Handle fcmp with constant RHS
5278 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5279 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5280 switch (LHSI->getOpcode()) {
5281 case Instruction::PHI:
5282 if (Instruction *NV = FoldOpIntoPhi(I))
5283 return NV;
5284 break;
5285 case Instruction::Select:
5286 // If either operand of the select is a constant, we can fold the
5287 // comparison into the select arms, which will cause one to be
5288 // constant folded and the select turned into a bitwise or.
5289 Value *Op1 = 0, *Op2 = 0;
5290 if (LHSI->hasOneUse()) {
5291 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5292 // Fold the known value into the constant operand.
5293 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5294 // Insert a new FCmp of the other select operand.
5295 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5296 LHSI->getOperand(2), RHSC,
5297 I.getName()), I);
5298 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5299 // Fold the known value into the constant operand.
5300 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5301 // Insert a new FCmp of the other select operand.
5302 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5303 LHSI->getOperand(1), RHSC,
5304 I.getName()), I);
5305 }
5306 }
5307
5308 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005309 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005310 break;
5311 }
5312 }
5313
5314 return Changed ? &I : 0;
5315}
5316
5317Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5318 bool Changed = SimplifyCompare(I);
5319 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5320 const Type *Ty = Op0->getType();
5321
5322 // icmp X, X
5323 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005324 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005325 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005326
5327 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005328 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005329
Reid Spencere4d87aa2006-12-23 06:05:41 +00005330 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005331 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005332 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5333 isa<ConstantPointerNull>(Op0)) &&
5334 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005335 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005336 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005337 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005338
Reid Spencere4d87aa2006-12-23 06:05:41 +00005339 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005340 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005341 switch (I.getPredicate()) {
5342 default: assert(0 && "Invalid icmp instruction!");
5343 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005344 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005345 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005346 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005347 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005348 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005349 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005350
Reid Spencere4d87aa2006-12-23 06:05:41 +00005351 case ICmpInst::ICMP_UGT:
5352 case ICmpInst::ICMP_SGT:
5353 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005354 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005355 case ICmpInst::ICMP_ULT:
5356 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005357 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005358 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005359 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005360 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005361 case ICmpInst::ICMP_UGE:
5362 case ICmpInst::ICMP_SGE:
5363 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005364 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005365 case ICmpInst::ICMP_ULE:
5366 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005367 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005368 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005369 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005370 }
5371 }
Chris Lattner8b170942002-08-09 23:47:40 +00005372 }
5373
Chris Lattner2be51ae2004-06-09 04:24:29 +00005374 // See if we are doing a comparison between a constant and an instruction that
5375 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005376 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005377 Value *A, *B;
5378
Chris Lattnerb6566012008-01-05 01:18:20 +00005379 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5380 if (I.isEquality() && CI->isNullValue() &&
5381 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5382 // (icmp cond A B) if cond is equality
5383 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005384 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005385
Reid Spencere4d87aa2006-12-23 06:05:41 +00005386 switch (I.getPredicate()) {
5387 default: break;
5388 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5389 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005390 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005391 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5392 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5393 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5394 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005395 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5396 if (CI->isMinValue(true))
5397 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5398 ConstantInt::getAllOnesValue(Op0->getType()));
5399
Reid Spencere4d87aa2006-12-23 06:05:41 +00005400 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005401
Reid Spencere4d87aa2006-12-23 06:05:41 +00005402 case ICmpInst::ICMP_SLT:
5403 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005404 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005405 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5406 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5407 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5408 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5409 break;
5410
5411 case ICmpInst::ICMP_UGT:
5412 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005413 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005414 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5415 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5416 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5417 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005418
5419 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5420 if (CI->isMaxValue(true))
5421 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5422 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005423 break;
5424
5425 case ICmpInst::ICMP_SGT:
5426 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005427 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005428 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5429 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5430 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5431 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5432 break;
5433
5434 case ICmpInst::ICMP_ULE:
5435 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005436 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005437 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5438 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5439 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5440 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5441 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005442
Reid Spencere4d87aa2006-12-23 06:05:41 +00005443 case ICmpInst::ICMP_SLE:
5444 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005445 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005446 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5447 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5448 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5449 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5450 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005451
Reid Spencere4d87aa2006-12-23 06:05:41 +00005452 case ICmpInst::ICMP_UGE:
5453 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005454 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005455 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5456 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5457 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5458 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5459 break;
5460
5461 case ICmpInst::ICMP_SGE:
5462 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005463 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005464 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5465 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5466 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5467 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5468 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005469 }
5470
Reid Spencere4d87aa2006-12-23 06:05:41 +00005471 // If we still have a icmp le or icmp ge instruction, turn it into the
5472 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005473 // already been handled above, this requires little checking.
5474 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005475 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005476 default: break;
5477 case ICmpInst::ICMP_ULE:
5478 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5479 case ICmpInst::ICMP_SLE:
5480 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5481 case ICmpInst::ICMP_UGE:
5482 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5483 case ICmpInst::ICMP_SGE:
5484 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005485 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005486
5487 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005488 // in the input. If this comparison is a normal comparison, it demands all
5489 // bits, if it is a sign bit comparison, it only demands the sign bit.
5490
5491 bool UnusedBit;
5492 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5493
Reid Spencer0460fb32007-03-22 20:36:03 +00005494 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5495 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005496 if (SimplifyDemandedBits(Op0,
5497 isSignBit ? APInt::getSignBit(BitWidth)
5498 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005499 KnownZero, KnownOne, 0))
5500 return &I;
5501
5502 // Given the known and unknown bits, compute a range that the LHS could be
5503 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005504 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005505 // Compute the Min, Max and RHS values based on the known bits. For the
5506 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005507 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5508 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005509 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005510 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5511 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005512 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005513 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5514 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005515 }
5516 switch (I.getPredicate()) { // LE/GE have been folded already.
5517 default: assert(0 && "Unknown icmp opcode!");
5518 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005519 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005520 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005521 break;
5522 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005523 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005524 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005525 break;
5526 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005527 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005528 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005529 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005530 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005531 break;
5532 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005533 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005534 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005535 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005536 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005537 break;
5538 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005539 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005540 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005541 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005542 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005543 break;
5544 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005545 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005546 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005547 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005548 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005549 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005550 }
5551 }
5552
Reid Spencere4d87aa2006-12-23 06:05:41 +00005553 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005554 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005555 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005556 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005557 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5558 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005559 }
5560
Chris Lattner01deb9d2007-04-03 17:43:25 +00005561 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005562 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5563 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5564 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005565 case Instruction::GetElementPtr:
5566 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005567 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005568 bool isAllZeros = true;
5569 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5570 if (!isa<Constant>(LHSI->getOperand(i)) ||
5571 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5572 isAllZeros = false;
5573 break;
5574 }
5575 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005576 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005577 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5578 }
5579 break;
5580
Chris Lattner6970b662005-04-23 15:31:55 +00005581 case Instruction::PHI:
5582 if (Instruction *NV = FoldOpIntoPhi(I))
5583 return NV;
5584 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005585 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005586 // If either operand of the select is a constant, we can fold the
5587 // comparison into the select arms, which will cause one to be
5588 // constant folded and the select turned into a bitwise or.
5589 Value *Op1 = 0, *Op2 = 0;
5590 if (LHSI->hasOneUse()) {
5591 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5592 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005593 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5594 // Insert a new ICmp of the other select operand.
5595 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5596 LHSI->getOperand(2), RHSC,
5597 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005598 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5599 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005600 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5601 // Insert a new ICmp of the other select operand.
5602 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5603 LHSI->getOperand(1), RHSC,
5604 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005605 }
5606 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005607
Chris Lattner6970b662005-04-23 15:31:55 +00005608 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005609 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005610 break;
5611 }
Chris Lattner4802d902007-04-06 18:57:34 +00005612 case Instruction::Malloc:
5613 // If we have (malloc != null), and if the malloc has a single use, we
5614 // can assume it is successful and remove the malloc.
5615 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5616 AddToWorkList(LHSI);
5617 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005618 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005619 }
5620 break;
5621 }
Chris Lattner6970b662005-04-23 15:31:55 +00005622 }
5623
Reid Spencere4d87aa2006-12-23 06:05:41 +00005624 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005625 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005626 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005627 return NI;
5628 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005629 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5630 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005631 return NI;
5632
Reid Spencere4d87aa2006-12-23 06:05:41 +00005633 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005634 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5635 // now.
5636 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5637 if (isa<PointerType>(Op0->getType()) &&
5638 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005639 // We keep moving the cast from the left operand over to the right
5640 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005641 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005642
Chris Lattner57d86372007-01-06 01:45:59 +00005643 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5644 // so eliminate it as well.
5645 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5646 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005647
Chris Lattnerde90b762003-11-03 04:25:02 +00005648 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005649 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005650 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005651 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005652 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005653 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005654 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005655 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005656 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005657 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005658 }
Chris Lattner57d86372007-01-06 01:45:59 +00005659 }
5660
5661 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005662 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005663 // This comes up when you have code like
5664 // int X = A < B;
5665 // if (X) ...
5666 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005667 // with a constant or another cast from the same type.
5668 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005669 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005670 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005671 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005672
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005673 // ~x < ~y --> y < x
5674 { Value *A, *B;
5675 if (match(Op0, m_Not(m_Value(A))) &&
5676 match(Op1, m_Not(m_Value(B))))
5677 return new ICmpInst(I.getPredicate(), B, A);
5678 }
5679
Chris Lattner65b72ba2006-09-18 04:22:48 +00005680 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005681 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005682
5683 // -x == -y --> x == y
5684 if (match(Op0, m_Neg(m_Value(A))) &&
5685 match(Op1, m_Neg(m_Value(B))))
5686 return new ICmpInst(I.getPredicate(), A, B);
5687
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005688 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5689 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5690 Value *OtherVal = A == Op1 ? B : A;
5691 return new ICmpInst(I.getPredicate(), OtherVal,
5692 Constant::getNullValue(A->getType()));
5693 }
5694
5695 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5696 // A^c1 == C^c2 --> A == C^(c1^c2)
5697 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5698 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5699 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005700 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005701 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005702 return new ICmpInst(I.getPredicate(), A,
5703 InsertNewInstBefore(Xor, I));
5704 }
5705
5706 // A^B == A^D -> B == D
5707 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5708 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5709 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5710 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5711 }
5712 }
5713
5714 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5715 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005716 // A == (A^B) -> B == 0
5717 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005718 return new ICmpInst(I.getPredicate(), OtherVal,
5719 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005720 }
5721 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005722 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005723 return new ICmpInst(I.getPredicate(), B,
5724 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005725 }
5726 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005727 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005728 return new ICmpInst(I.getPredicate(), B,
5729 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005730 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005731
Chris Lattner9c2328e2006-11-14 06:06:06 +00005732 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5733 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5734 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5735 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5736 Value *X = 0, *Y = 0, *Z = 0;
5737
5738 if (A == C) {
5739 X = B; Y = D; Z = A;
5740 } else if (A == D) {
5741 X = B; Y = C; Z = A;
5742 } else if (B == C) {
5743 X = A; Y = D; Z = B;
5744 } else if (B == D) {
5745 X = A; Y = C; Z = B;
5746 }
5747
5748 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005749 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5750 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005751 I.setOperand(0, Op1);
5752 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5753 return &I;
5754 }
5755 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005756 }
Chris Lattner7e708292002-06-25 16:13:24 +00005757 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005758}
5759
Chris Lattner562ef782007-06-20 23:46:26 +00005760
5761/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5762/// and CmpRHS are both known to be integer constants.
5763Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5764 ConstantInt *DivRHS) {
5765 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5766 const APInt &CmpRHSV = CmpRHS->getValue();
5767
5768 // FIXME: If the operand types don't match the type of the divide
5769 // then don't attempt this transform. The code below doesn't have the
5770 // logic to deal with a signed divide and an unsigned compare (and
5771 // vice versa). This is because (x /s C1) <s C2 produces different
5772 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5773 // (x /u C1) <u C2. Simply casting the operands and result won't
5774 // work. :( The if statement below tests that condition and bails
5775 // if it finds it.
5776 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5777 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5778 return 0;
5779 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005780 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005781
5782 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5783 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5784 // C2 (CI). By solving for X we can turn this into a range check
5785 // instead of computing a divide.
5786 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5787
5788 // Determine if the product overflows by seeing if the product is
5789 // not equal to the divide. Make sure we do the same kind of divide
5790 // as in the LHS instruction that we're folding.
5791 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5792 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5793
5794 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005795 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005796
Chris Lattner1dbfd482007-06-21 18:11:19 +00005797 // Figure out the interval that is being checked. For example, a comparison
5798 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5799 // Compute this interval based on the constants involved and the signedness of
5800 // the compare/divide. This computes a half-open interval, keeping track of
5801 // whether either value in the interval overflows. After analysis each
5802 // overflow variable is set to 0 if it's corresponding bound variable is valid
5803 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5804 int LoOverflow = 0, HiOverflow = 0;
5805 ConstantInt *LoBound = 0, *HiBound = 0;
5806
5807
Chris Lattner562ef782007-06-20 23:46:26 +00005808 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005809 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005810 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005811 HiOverflow = LoOverflow = ProdOV;
5812 if (!HiOverflow)
5813 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005814 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005815 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005816 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005817 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5818 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005819 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005820 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5821 HiOverflow = LoOverflow = ProdOV;
5822 if (!HiOverflow)
5823 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005824 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005825 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005826 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5827 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005828 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005829 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005830 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005831 }
Dan Gohman76491272008-02-13 22:09:18 +00005832 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005833 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005834 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005835 LoBound = AddOne(DivRHS);
5836 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005837 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5838 HiOverflow = 1; // [INTMIN+1, overflow)
5839 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5840 }
Dan Gohman76491272008-02-13 22:09:18 +00005841 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005842 // e.g. X/-5 op 3 --> [-19, -14)
5843 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005844 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005845 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005846 HiBound = AddOne(Prod);
5847 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005848 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005849 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005850 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005851 HiBound = Subtract(Prod, DivRHS);
5852 }
5853
Chris Lattner1dbfd482007-06-21 18:11:19 +00005854 // Dividing by a negative swaps the condition. LT <-> GT
5855 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005856 }
5857
5858 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005859 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005860 default: assert(0 && "Unhandled icmp opcode!");
5861 case ICmpInst::ICMP_EQ:
5862 if (LoOverflow && HiOverflow)
5863 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5864 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005865 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005866 ICmpInst::ICMP_UGE, X, LoBound);
5867 else if (LoOverflow)
5868 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5869 ICmpInst::ICMP_ULT, X, HiBound);
5870 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005871 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005872 case ICmpInst::ICMP_NE:
5873 if (LoOverflow && HiOverflow)
5874 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5875 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005876 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005877 ICmpInst::ICMP_ULT, X, LoBound);
5878 else if (LoOverflow)
5879 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5880 ICmpInst::ICMP_UGE, X, HiBound);
5881 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005882 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005883 case ICmpInst::ICMP_ULT:
5884 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005885 if (LoOverflow == +1) // Low bound is greater than input range.
5886 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5887 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005888 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005889 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005890 case ICmpInst::ICMP_UGT:
5891 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005892 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005893 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005894 else if (HiOverflow == -1) // High bound less than input range.
5895 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5896 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005897 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5898 else
5899 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5900 }
5901}
5902
5903
Chris Lattner01deb9d2007-04-03 17:43:25 +00005904/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5905///
5906Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5907 Instruction *LHSI,
5908 ConstantInt *RHS) {
5909 const APInt &RHSV = RHS->getValue();
5910
5911 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005912 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005913 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5914 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5915 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005916 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5917 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005918 Value *CompareVal = LHSI->getOperand(0);
5919
5920 // If the sign bit of the XorCST is not set, there is no change to
5921 // the operation, just stop using the Xor.
5922 if (!XorCST->getValue().isNegative()) {
5923 ICI.setOperand(0, CompareVal);
5924 AddToWorkList(LHSI);
5925 return &ICI;
5926 }
5927
5928 // Was the old condition true if the operand is positive?
5929 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5930
5931 // If so, the new one isn't.
5932 isTrueIfPositive ^= true;
5933
5934 if (isTrueIfPositive)
5935 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5936 else
5937 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5938 }
5939 }
5940 break;
5941 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5942 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5943 LHSI->getOperand(0)->hasOneUse()) {
5944 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5945
5946 // If the LHS is an AND of a truncating cast, we can widen the
5947 // and/compare to be the input width without changing the value
5948 // produced, eliminating a cast.
5949 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5950 // We can do this transformation if either the AND constant does not
5951 // have its sign bit set or if it is an equality comparison.
5952 // Extending a relational comparison when we're checking the sign
5953 // bit would not work.
5954 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005955 (ICI.isEquality() ||
5956 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005957 uint32_t BitWidth =
5958 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5959 APInt NewCST = AndCST->getValue();
5960 NewCST.zext(BitWidth);
5961 APInt NewCI = RHSV;
5962 NewCI.zext(BitWidth);
5963 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005964 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00005965 ConstantInt::get(NewCST),LHSI->getName());
5966 InsertNewInstBefore(NewAnd, ICI);
5967 return new ICmpInst(ICI.getPredicate(), NewAnd,
5968 ConstantInt::get(NewCI));
5969 }
5970 }
5971
5972 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5973 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5974 // happens a LOT in code produced by the C front-end, for bitfield
5975 // access.
5976 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5977 if (Shift && !Shift->isShift())
5978 Shift = 0;
5979
5980 ConstantInt *ShAmt;
5981 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5982 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5983 const Type *AndTy = AndCST->getType(); // Type of the and.
5984
5985 // We can fold this as long as we can't shift unknown bits
5986 // into the mask. This can only happen with signed shift
5987 // rights, as they sign-extend.
5988 if (ShAmt) {
5989 bool CanFold = Shift->isLogicalShift();
5990 if (!CanFold) {
5991 // To test for the bad case of the signed shr, see if any
5992 // of the bits shifted in could be tested after the mask.
5993 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5994 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5995
5996 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5997 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5998 AndCST->getValue()) == 0)
5999 CanFold = true;
6000 }
6001
6002 if (CanFold) {
6003 Constant *NewCst;
6004 if (Shift->getOpcode() == Instruction::Shl)
6005 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6006 else
6007 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6008
6009 // Check to see if we are shifting out any of the bits being
6010 // compared.
6011 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6012 // If we shifted bits out, the fold is not going to work out.
6013 // As a special case, check to see if this means that the
6014 // result is always true or false now.
6015 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6016 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6017 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6018 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6019 } else {
6020 ICI.setOperand(1, NewCst);
6021 Constant *NewAndCST;
6022 if (Shift->getOpcode() == Instruction::Shl)
6023 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6024 else
6025 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6026 LHSI->setOperand(1, NewAndCST);
6027 LHSI->setOperand(0, Shift->getOperand(0));
6028 AddToWorkList(Shift); // Shift is dead.
6029 AddUsesToWorkList(ICI);
6030 return &ICI;
6031 }
6032 }
6033 }
6034
6035 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6036 // preferable because it allows the C<<Y expression to be hoisted out
6037 // of a loop if Y is invariant and X is not.
6038 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6039 ICI.isEquality() && !Shift->isArithmeticShift() &&
6040 isa<Instruction>(Shift->getOperand(0))) {
6041 // Compute C << Y.
6042 Value *NS;
6043 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006044 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006045 Shift->getOperand(1), "tmp");
6046 } else {
6047 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006048 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006049 Shift->getOperand(1), "tmp");
6050 }
6051 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6052
6053 // Compute X & (C << Y).
6054 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006055 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006056 InsertNewInstBefore(NewAnd, ICI);
6057
6058 ICI.setOperand(0, NewAnd);
6059 return &ICI;
6060 }
6061 }
6062 break;
6063
Chris Lattnera0141b92007-07-15 20:42:37 +00006064 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6065 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6066 if (!ShAmt) break;
6067
6068 uint32_t TypeBits = RHSV.getBitWidth();
6069
6070 // Check that the shift amount is in range. If not, don't perform
6071 // undefined shifts. When the shift is visited it will be
6072 // simplified.
6073 if (ShAmt->uge(TypeBits))
6074 break;
6075
6076 if (ICI.isEquality()) {
6077 // If we are comparing against bits always shifted out, the
6078 // comparison cannot succeed.
6079 Constant *Comp =
6080 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6081 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6082 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6083 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6084 return ReplaceInstUsesWith(ICI, Cst);
6085 }
6086
6087 if (LHSI->hasOneUse()) {
6088 // Otherwise strength reduce the shift into an and.
6089 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6090 Constant *Mask =
6091 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006092
Chris Lattnera0141b92007-07-15 20:42:37 +00006093 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006094 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006095 Mask, LHSI->getName()+".mask");
6096 Value *And = InsertNewInstBefore(AndI, ICI);
6097 return new ICmpInst(ICI.getPredicate(), And,
6098 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006099 }
6100 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006101
6102 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6103 bool TrueIfSigned = false;
6104 if (LHSI->hasOneUse() &&
6105 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6106 // (X << 31) <s 0 --> (X&1) != 0
6107 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6108 (TypeBits-ShAmt->getZExtValue()-1));
6109 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006110 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006111 Mask, LHSI->getName()+".mask");
6112 Value *And = InsertNewInstBefore(AndI, ICI);
6113
6114 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6115 And, Constant::getNullValue(And->getType()));
6116 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006117 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006118 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006119
6120 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006121 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006122 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006123 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006124 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006125
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006126 // Check that the shift amount is in range. If not, don't perform
6127 // undefined shifts. When the shift is visited it will be
6128 // simplified.
6129 uint32_t TypeBits = RHSV.getBitWidth();
6130 if (ShAmt->uge(TypeBits))
6131 break;
6132
6133 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006134
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006135 // If we are comparing against bits always shifted out, the
6136 // comparison cannot succeed.
6137 APInt Comp = RHSV << ShAmtVal;
6138 if (LHSI->getOpcode() == Instruction::LShr)
6139 Comp = Comp.lshr(ShAmtVal);
6140 else
6141 Comp = Comp.ashr(ShAmtVal);
6142
6143 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6144 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6145 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6146 return ReplaceInstUsesWith(ICI, Cst);
6147 }
6148
6149 // Otherwise, check to see if the bits shifted out are known to be zero.
6150 // If so, we can compare against the unshifted value:
6151 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006152 if (LHSI->hasOneUse() &&
6153 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006154 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6155 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6156 ConstantExpr::getShl(RHS, ShAmt));
6157 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006158
Evan Chengf30752c2008-04-23 00:38:06 +00006159 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006160 // Otherwise strength reduce the shift into an and.
6161 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6162 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006163
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006164 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006165 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006166 Mask, LHSI->getName()+".mask");
6167 Value *And = InsertNewInstBefore(AndI, ICI);
6168 return new ICmpInst(ICI.getPredicate(), And,
6169 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006170 }
6171 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006172 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006173
6174 case Instruction::SDiv:
6175 case Instruction::UDiv:
6176 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6177 // Fold this div into the comparison, producing a range check.
6178 // Determine, based on the divide type, what the range is being
6179 // checked. If there is an overflow on the low or high side, remember
6180 // it, otherwise compute the range [low, hi) bounding the new value.
6181 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006182 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6183 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6184 DivRHS))
6185 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006186 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006187
6188 case Instruction::Add:
6189 // Fold: icmp pred (add, X, C1), C2
6190
6191 if (!ICI.isEquality()) {
6192 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6193 if (!LHSC) break;
6194 const APInt &LHSV = LHSC->getValue();
6195
6196 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6197 .subtract(LHSV);
6198
6199 if (ICI.isSignedPredicate()) {
6200 if (CR.getLower().isSignBit()) {
6201 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6202 ConstantInt::get(CR.getUpper()));
6203 } else if (CR.getUpper().isSignBit()) {
6204 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6205 ConstantInt::get(CR.getLower()));
6206 }
6207 } else {
6208 if (CR.getLower().isMinValue()) {
6209 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6210 ConstantInt::get(CR.getUpper()));
6211 } else if (CR.getUpper().isMinValue()) {
6212 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6213 ConstantInt::get(CR.getLower()));
6214 }
6215 }
6216 }
6217 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006218 }
6219
6220 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6221 if (ICI.isEquality()) {
6222 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6223
6224 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6225 // the second operand is a constant, simplify a bit.
6226 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6227 switch (BO->getOpcode()) {
6228 case Instruction::SRem:
6229 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6230 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6231 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6232 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6233 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006234 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006235 BO->getName());
6236 InsertNewInstBefore(NewRem, ICI);
6237 return new ICmpInst(ICI.getPredicate(), NewRem,
6238 Constant::getNullValue(BO->getType()));
6239 }
6240 }
6241 break;
6242 case Instruction::Add:
6243 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6244 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6245 if (BO->hasOneUse())
6246 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6247 Subtract(RHS, BOp1C));
6248 } else if (RHSV == 0) {
6249 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6250 // efficiently invertible, or if the add has just this one use.
6251 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6252
6253 if (Value *NegVal = dyn_castNegVal(BOp1))
6254 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6255 else if (Value *NegVal = dyn_castNegVal(BOp0))
6256 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6257 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006258 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006259 InsertNewInstBefore(Neg, ICI);
6260 Neg->takeName(BO);
6261 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6262 }
6263 }
6264 break;
6265 case Instruction::Xor:
6266 // For the xor case, we can xor two constants together, eliminating
6267 // the explicit xor.
6268 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6269 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6270 ConstantExpr::getXor(RHS, BOC));
6271
6272 // FALLTHROUGH
6273 case Instruction::Sub:
6274 // Replace (([sub|xor] A, B) != 0) with (A != B)
6275 if (RHSV == 0)
6276 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6277 BO->getOperand(1));
6278 break;
6279
6280 case Instruction::Or:
6281 // If bits are being or'd in that are not present in the constant we
6282 // are comparing against, then the comparison could never succeed!
6283 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6284 Constant *NotCI = ConstantExpr::getNot(RHS);
6285 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6286 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6287 isICMP_NE));
6288 }
6289 break;
6290
6291 case Instruction::And:
6292 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6293 // If bits are being compared against that are and'd out, then the
6294 // comparison can never succeed!
6295 if ((RHSV & ~BOC->getValue()) != 0)
6296 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6297 isICMP_NE));
6298
6299 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6300 if (RHS == BOC && RHSV.isPowerOf2())
6301 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6302 ICmpInst::ICMP_NE, LHSI,
6303 Constant::getNullValue(RHS->getType()));
6304
6305 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6306 if (isSignBit(BOC)) {
6307 Value *X = BO->getOperand(0);
6308 Constant *Zero = Constant::getNullValue(X->getType());
6309 ICmpInst::Predicate pred = isICMP_NE ?
6310 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6311 return new ICmpInst(pred, X, Zero);
6312 }
6313
6314 // ((X & ~7) == 0) --> X < 8
6315 if (RHSV == 0 && isHighOnes(BOC)) {
6316 Value *X = BO->getOperand(0);
6317 Constant *NegX = ConstantExpr::getNeg(BOC);
6318 ICmpInst::Predicate pred = isICMP_NE ?
6319 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6320 return new ICmpInst(pred, X, NegX);
6321 }
6322 }
6323 default: break;
6324 }
6325 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6326 // Handle icmp {eq|ne} <intrinsic>, intcst.
6327 if (II->getIntrinsicID() == Intrinsic::bswap) {
6328 AddToWorkList(II);
6329 ICI.setOperand(0, II->getOperand(1));
6330 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6331 return &ICI;
6332 }
6333 }
6334 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006335 // If the LHS is a cast from an integral value of the same size,
6336 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006337 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6338 Value *CastOp = Cast->getOperand(0);
6339 const Type *SrcTy = CastOp->getType();
6340 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6341 if (SrcTy->isInteger() &&
6342 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6343 // If this is an unsigned comparison, try to make the comparison use
6344 // smaller constant values.
6345 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6346 // X u< 128 => X s> -1
6347 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6348 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6349 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6350 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6351 // X u> 127 => X s< 0
6352 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6353 Constant::getNullValue(SrcTy));
6354 }
6355 }
6356 }
6357 }
6358 return 0;
6359}
6360
6361/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6362/// We only handle extending casts so far.
6363///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006364Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6365 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006366 Value *LHSCIOp = LHSCI->getOperand(0);
6367 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006368 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006369 Value *RHSCIOp;
6370
Chris Lattner8c756c12007-05-05 22:41:33 +00006371 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6372 // integer type is the same size as the pointer type.
6373 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6374 getTargetData().getPointerSizeInBits() ==
6375 cast<IntegerType>(DestTy)->getBitWidth()) {
6376 Value *RHSOp = 0;
6377 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006378 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006379 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6380 RHSOp = RHSC->getOperand(0);
6381 // If the pointer types don't match, insert a bitcast.
6382 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006383 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006384 }
6385
6386 if (RHSOp)
6387 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6388 }
6389
6390 // The code below only handles extension cast instructions, so far.
6391 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006392 if (LHSCI->getOpcode() != Instruction::ZExt &&
6393 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006394 return 0;
6395
Reid Spencere4d87aa2006-12-23 06:05:41 +00006396 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6397 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006398
Reid Spencere4d87aa2006-12-23 06:05:41 +00006399 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006400 // Not an extension from the same type?
6401 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006402 if (RHSCIOp->getType() != LHSCIOp->getType())
6403 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006404
Nick Lewycky4189a532008-01-28 03:48:02 +00006405 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006406 // and the other is a zext), then we can't handle this.
6407 if (CI->getOpcode() != LHSCI->getOpcode())
6408 return 0;
6409
Nick Lewycky4189a532008-01-28 03:48:02 +00006410 // Deal with equality cases early.
6411 if (ICI.isEquality())
6412 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6413
6414 // A signed comparison of sign extended values simplifies into a
6415 // signed comparison.
6416 if (isSignedCmp && isSignedExt)
6417 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6418
6419 // The other three cases all fold into an unsigned comparison.
6420 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006421 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006422
Reid Spencere4d87aa2006-12-23 06:05:41 +00006423 // If we aren't dealing with a constant on the RHS, exit early
6424 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6425 if (!CI)
6426 return 0;
6427
6428 // Compute the constant that would happen if we truncated to SrcTy then
6429 // reextended to DestTy.
6430 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6431 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6432
6433 // If the re-extended constant didn't change...
6434 if (Res2 == CI) {
6435 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6436 // For example, we might have:
6437 // %A = sext short %X to uint
6438 // %B = icmp ugt uint %A, 1330
6439 // It is incorrect to transform this into
6440 // %B = icmp ugt short %X, 1330
6441 // because %A may have negative value.
6442 //
6443 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6444 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006445 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006446 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6447 else
6448 return 0;
6449 }
6450
6451 // The re-extended constant changed so the constant cannot be represented
6452 // in the shorter type. Consequently, we cannot emit a simple comparison.
6453
6454 // First, handle some easy cases. We know the result cannot be equal at this
6455 // point so handle the ICI.isEquality() cases
6456 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006457 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006458 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006459 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006460
6461 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6462 // should have been folded away previously and not enter in here.
6463 Value *Result;
6464 if (isSignedCmp) {
6465 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006466 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006467 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006468 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006469 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006470 } else {
6471 // We're performing an unsigned comparison.
6472 if (isSignedExt) {
6473 // We're performing an unsigned comp with a sign extended value.
6474 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006475 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006476 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6477 NegOne, ICI.getName()), ICI);
6478 } else {
6479 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006480 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006481 }
6482 }
6483
6484 // Finally, return the value computed.
6485 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6486 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6487 return ReplaceInstUsesWith(ICI, Result);
6488 } else {
6489 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6490 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6491 "ICmp should be folded!");
6492 if (Constant *CI = dyn_cast<Constant>(Result))
6493 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6494 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006495 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006496 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006497}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006498
Reid Spencer832254e2007-02-02 02:16:23 +00006499Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6500 return commonShiftTransforms(I);
6501}
6502
6503Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6504 return commonShiftTransforms(I);
6505}
6506
6507Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006508 if (Instruction *R = commonShiftTransforms(I))
6509 return R;
6510
6511 Value *Op0 = I.getOperand(0);
6512
6513 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6514 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6515 if (CSI->isAllOnesValue())
6516 return ReplaceInstUsesWith(I, CSI);
6517
6518 // See if we can turn a signed shr into an unsigned shr.
6519 if (MaskedValueIsZero(Op0,
6520 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006521 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006522
6523 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006524}
6525
6526Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6527 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006528 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006529
6530 // shl X, 0 == X and shr X, 0 == X
6531 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006532 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006533 Op0 == Constant::getNullValue(Op0->getType()))
6534 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006535
Reid Spencere4d87aa2006-12-23 06:05:41 +00006536 if (isa<UndefValue>(Op0)) {
6537 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006538 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006539 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006540 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6541 }
6542 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006543 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6544 return ReplaceInstUsesWith(I, Op0);
6545 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006546 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006547 }
6548
Chris Lattner2eefe512004-04-09 19:05:30 +00006549 // Try to fold constant and into select arguments.
6550 if (isa<Constant>(Op0))
6551 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006552 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006553 return R;
6554
Reid Spencerb83eb642006-10-20 07:07:24 +00006555 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006556 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6557 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006558 return 0;
6559}
6560
Reid Spencerb83eb642006-10-20 07:07:24 +00006561Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006562 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006563 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006564
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006565 // See if we can simplify any instructions used by the instruction whose sole
6566 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006567 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6568 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6569 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006570 KnownZero, KnownOne))
6571 return &I;
6572
Chris Lattner4d5542c2006-01-06 07:12:35 +00006573 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6574 // of a signed value.
6575 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006576 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006577 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006578 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6579 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006580 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006581 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006582 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006583 }
6584
6585 // ((X*C1) << C2) == (X * (C1 << C2))
6586 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6587 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6588 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006589 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006590 ConstantExpr::getShl(BOOp, Op1));
6591
6592 // Try to fold constant and into select arguments.
6593 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6594 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6595 return R;
6596 if (isa<PHINode>(Op0))
6597 if (Instruction *NV = FoldOpIntoPhi(I))
6598 return NV;
6599
Chris Lattner8999dd32007-12-22 09:07:47 +00006600 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6601 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6602 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6603 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6604 // place. Don't try to do this transformation in this case. Also, we
6605 // require that the input operand is a shift-by-constant so that we have
6606 // confidence that the shifts will get folded together. We could do this
6607 // xform in more cases, but it is unlikely to be profitable.
6608 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6609 isa<ConstantInt>(TrOp->getOperand(1))) {
6610 // Okay, we'll do this xform. Make the shift of shift.
6611 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006612 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006613 I.getName());
6614 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6615
6616 // For logical shifts, the truncation has the effect of making the high
6617 // part of the register be zeros. Emulate this by inserting an AND to
6618 // clear the top bits as needed. This 'and' will usually be zapped by
6619 // other xforms later if dead.
6620 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6621 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6622 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6623
6624 // The mask we constructed says what the trunc would do if occurring
6625 // between the shifts. We want to know the effect *after* the second
6626 // shift. We know that it is a logical shift by a constant, so adjust the
6627 // mask as appropriate.
6628 if (I.getOpcode() == Instruction::Shl)
6629 MaskV <<= Op1->getZExtValue();
6630 else {
6631 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6632 MaskV = MaskV.lshr(Op1->getZExtValue());
6633 }
6634
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006635 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006636 TI->getName());
6637 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6638
6639 // Return the value truncated to the interesting size.
6640 return new TruncInst(And, I.getType());
6641 }
6642 }
6643
Chris Lattner4d5542c2006-01-06 07:12:35 +00006644 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006645 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6646 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6647 Value *V1, *V2;
6648 ConstantInt *CC;
6649 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006650 default: break;
6651 case Instruction::Add:
6652 case Instruction::And:
6653 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006654 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006655 // These operators commute.
6656 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006657 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6658 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006659 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006660 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006661 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006662 Op0BO->getName());
6663 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006664 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006665 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006666 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006667 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006668 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006669 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006670 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006671 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006672
Chris Lattner150f12a2005-09-18 06:30:59 +00006673 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006674 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006675 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006676 match(Op0BOOp1,
6677 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006678 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6679 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006680 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006681 Op0BO->getOperand(0), Op1,
6682 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006683 InsertNewInstBefore(YS, I); // (Y << C)
6684 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006685 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006686 V1->getName()+".mask");
6687 InsertNewInstBefore(XM, I); // X & (CC << C)
6688
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006689 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006690 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006691 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006692
Reid Spencera07cb7d2007-02-02 14:41:37 +00006693 // FALL THROUGH.
6694 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006695 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006696 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6697 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006698 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006699 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006700 Op0BO->getOperand(1), Op1,
6701 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006702 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006703 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006704 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006705 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006706 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006707 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006708 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006709 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006710 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006711
Chris Lattner13d4ab42006-05-31 21:14:00 +00006712 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006713 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6714 match(Op0BO->getOperand(0),
6715 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006716 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006717 cast<BinaryOperator>(Op0BO->getOperand(0))
6718 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006719 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006720 Op0BO->getOperand(1), Op1,
6721 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006722 InsertNewInstBefore(YS, I); // (Y << C)
6723 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006724 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006725 V1->getName()+".mask");
6726 InsertNewInstBefore(XM, I); // X & (CC << C)
6727
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006728 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006729 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006730
Chris Lattner11021cb2005-09-18 05:12:10 +00006731 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006732 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006733 }
6734
6735
6736 // If the operand is an bitwise operator with a constant RHS, and the
6737 // shift is the only use, we can pull it out of the shift.
6738 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6739 bool isValid = true; // Valid only for And, Or, Xor
6740 bool highBitSet = false; // Transform if high bit of constant set?
6741
6742 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006743 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006744 case Instruction::Add:
6745 isValid = isLeftShift;
6746 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006747 case Instruction::Or:
6748 case Instruction::Xor:
6749 highBitSet = false;
6750 break;
6751 case Instruction::And:
6752 highBitSet = true;
6753 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006754 }
6755
6756 // If this is a signed shift right, and the high bit is modified
6757 // by the logical operation, do not perform the transformation.
6758 // The highBitSet boolean indicates the value of the high bit of
6759 // the constant which would cause it to be modified for this
6760 // operation.
6761 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006762 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006763 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006764
6765 if (isValid) {
6766 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6767
6768 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006769 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006770 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006771 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006772
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006773 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006774 NewRHS);
6775 }
6776 }
6777 }
6778 }
6779
Chris Lattnerad0124c2006-01-06 07:52:12 +00006780 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006781 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6782 if (ShiftOp && !ShiftOp->isShift())
6783 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006784
Reid Spencerb83eb642006-10-20 07:07:24 +00006785 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006786 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006787 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6788 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006789 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6790 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6791 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006792
Zhou Sheng4351c642007-04-02 08:20:41 +00006793 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006794 if (AmtSum > TypeBits)
6795 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006796
6797 const IntegerType *Ty = cast<IntegerType>(I.getType());
6798
6799 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006800 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006801 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006802 ConstantInt::get(Ty, AmtSum));
6803 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6804 I.getOpcode() == Instruction::AShr) {
6805 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006806 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006807 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6808 I.getOpcode() == Instruction::LShr) {
6809 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6810 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006811 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006812 InsertNewInstBefore(Shift, I);
6813
Zhou Shenge9e03f62007-03-28 15:02:20 +00006814 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006815 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006816 }
6817
Chris Lattnerb87056f2007-02-05 00:57:54 +00006818 // Okay, if we get here, one shift must be left, and the other shift must be
6819 // right. See if the amounts are equal.
6820 if (ShiftAmt1 == ShiftAmt2) {
6821 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6822 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006823 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006824 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006825 }
6826 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6827 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006828 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006829 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006830 }
6831 // We can simplify ((X << C) >>s C) into a trunc + sext.
6832 // NOTE: we could do this for any C, but that would make 'unusual' integer
6833 // types. For now, just stick to ones well-supported by the code
6834 // generators.
6835 const Type *SExtType = 0;
6836 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006837 case 1 :
6838 case 8 :
6839 case 16 :
6840 case 32 :
6841 case 64 :
6842 case 128:
6843 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6844 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006845 default: break;
6846 }
6847 if (SExtType) {
6848 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6849 InsertNewInstBefore(NewTrunc, I);
6850 return new SExtInst(NewTrunc, Ty);
6851 }
6852 // Otherwise, we can't handle it yet.
6853 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006854 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006855
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006856 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006857 if (I.getOpcode() == Instruction::Shl) {
6858 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6859 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006860 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006861 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006862 InsertNewInstBefore(Shift, I);
6863
Reid Spencer55702aa2007-03-25 21:11:44 +00006864 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006865 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006866 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006867
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006868 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006869 if (I.getOpcode() == Instruction::LShr) {
6870 assert(ShiftOp->getOpcode() == Instruction::Shl);
6871 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006872 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006873 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006874
Reid Spencerd5e30f02007-03-26 17:18:58 +00006875 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006876 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006877 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006878
6879 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6880 } else {
6881 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006882 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006883
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006884 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006885 if (I.getOpcode() == Instruction::Shl) {
6886 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6887 ShiftOp->getOpcode() == Instruction::AShr);
6888 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006889 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006890 ConstantInt::get(Ty, ShiftDiff));
6891 InsertNewInstBefore(Shift, I);
6892
Reid Spencer55702aa2007-03-25 21:11:44 +00006893 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006894 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006895 }
6896
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006897 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006898 if (I.getOpcode() == Instruction::LShr) {
6899 assert(ShiftOp->getOpcode() == Instruction::Shl);
6900 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006901 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006902 InsertNewInstBefore(Shift, I);
6903
Reid Spencer68d27cf2007-03-26 23:45:51 +00006904 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006905 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006906 }
6907
6908 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006909 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006910 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006911 return 0;
6912}
6913
Chris Lattnera1be5662002-05-02 17:06:02 +00006914
Chris Lattnercfd65102005-10-29 04:36:15 +00006915/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6916/// expression. If so, decompose it, returning some value X, such that Val is
6917/// X*Scale+Offset.
6918///
6919static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006920 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006921 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006922 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006923 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006924 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006925 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006926 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6927 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6928 if (I->getOpcode() == Instruction::Shl) {
6929 // This is a value scaled by '1 << the shift amt'.
6930 Scale = 1U << RHS->getZExtValue();
6931 Offset = 0;
6932 return I->getOperand(0);
6933 } else if (I->getOpcode() == Instruction::Mul) {
6934 // This value is scaled by 'RHS'.
6935 Scale = RHS->getZExtValue();
6936 Offset = 0;
6937 return I->getOperand(0);
6938 } else if (I->getOpcode() == Instruction::Add) {
6939 // We have X+C. Check to see if we really have (X*C2)+C1,
6940 // where C1 is divisible by C2.
6941 unsigned SubScale;
6942 Value *SubVal =
6943 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6944 Offset += RHS->getZExtValue();
6945 Scale = SubScale;
6946 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006947 }
6948 }
6949 }
6950
6951 // Otherwise, we can't look past this.
6952 Scale = 1;
6953 Offset = 0;
6954 return Val;
6955}
6956
6957
Chris Lattnerb3f83972005-10-24 06:03:58 +00006958/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6959/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006960Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006961 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006962 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006963
Chris Lattnerb53c2382005-10-24 06:22:12 +00006964 // Remove any uses of AI that are dead.
6965 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006966
Chris Lattnerb53c2382005-10-24 06:22:12 +00006967 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6968 Instruction *User = cast<Instruction>(*UI++);
6969 if (isInstructionTriviallyDead(User)) {
6970 while (UI != E && *UI == User)
6971 ++UI; // If this instruction uses AI more than once, don't break UI.
6972
Chris Lattnerb53c2382005-10-24 06:22:12 +00006973 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006974 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006975 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006976 }
6977 }
6978
Chris Lattnerb3f83972005-10-24 06:03:58 +00006979 // Get the type really allocated and the type casted to.
6980 const Type *AllocElTy = AI.getAllocatedType();
6981 const Type *CastElTy = PTy->getElementType();
6982 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006983
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006984 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6985 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006986 if (CastElTyAlign < AllocElTyAlign) return 0;
6987
Chris Lattner39387a52005-10-24 06:35:18 +00006988 // If the allocation has multiple uses, only promote it if we are strictly
6989 // increasing the alignment of the resultant allocation. If we keep it the
6990 // same, we open the door to infinite loops of various kinds.
6991 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6992
Duncan Sands514ab342007-11-01 20:53:16 +00006993 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6994 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006995 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006996
Chris Lattner455fcc82005-10-29 03:19:53 +00006997 // See if we can satisfy the modulus by pulling a scale out of the array
6998 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006999 unsigned ArraySizeScale;
7000 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007001 Value *NumElements = // See if the array size is a decomposable linear expr.
7002 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7003
Chris Lattner455fcc82005-10-29 03:19:53 +00007004 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7005 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007006 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7007 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007008
Chris Lattner455fcc82005-10-29 03:19:53 +00007009 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7010 Value *Amt = 0;
7011 if (Scale == 1) {
7012 Amt = NumElements;
7013 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007014 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007015 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7016 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007017 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007018 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007019 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007020 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007021 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007022 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007023 }
7024
Jeff Cohen86796be2007-04-04 16:58:57 +00007025 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7026 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007027 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007028 Amt = InsertNewInstBefore(Tmp, AI);
7029 }
7030
Chris Lattnerb3f83972005-10-24 06:03:58 +00007031 AllocationInst *New;
7032 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007033 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007034 else
Chris Lattner6934a042007-02-11 01:23:03 +00007035 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007036 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007037 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007038
7039 // If the allocation has multiple uses, insert a cast and change all things
7040 // that used it to use the new cast. This will also hack on CI, but it will
7041 // die soon.
7042 if (!AI.hasOneUse()) {
7043 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007044 // New is the allocation instruction, pointer typed. AI is the original
7045 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7046 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007047 InsertNewInstBefore(NewCast, AI);
7048 AI.replaceAllUsesWith(NewCast);
7049 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007050 return ReplaceInstUsesWith(CI, New);
7051}
7052
Chris Lattner70074e02006-05-13 02:06:03 +00007053/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007054/// and return it as type Ty without inserting any new casts and without
7055/// changing the computed value. This is used by code that tries to decide
7056/// whether promoting or shrinking integer operations to wider or smaller types
7057/// will allow us to eliminate a truncate or extend.
7058///
7059/// This is a truncation operation if Ty is smaller than V->getType(), or an
7060/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007061bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7062 unsigned CastOpc,
7063 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007064 // We can always evaluate constants in another type.
7065 if (isa<ConstantInt>(V))
7066 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007067
7068 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007069 if (!I) return false;
7070
7071 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007072
Chris Lattner951626b2007-08-02 06:11:14 +00007073 // If this is an extension or truncate, we can often eliminate it.
7074 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7075 // If this is a cast from the destination type, we can trivially eliminate
7076 // it, and this will remove a cast overall.
7077 if (I->getOperand(0)->getType() == Ty) {
7078 // If the first operand is itself a cast, and is eliminable, do not count
7079 // this as an eliminable cast. We would prefer to eliminate those two
7080 // casts first.
7081 if (!isa<CastInst>(I->getOperand(0)))
7082 ++NumCastsRemoved;
7083 return true;
7084 }
7085 }
7086
7087 // We can't extend or shrink something that has multiple uses: doing so would
7088 // require duplicating the instruction in general, which isn't profitable.
7089 if (!I->hasOneUse()) return false;
7090
Chris Lattner70074e02006-05-13 02:06:03 +00007091 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007092 case Instruction::Add:
7093 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007094 case Instruction::And:
7095 case Instruction::Or:
7096 case Instruction::Xor:
7097 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007098 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7099 NumCastsRemoved) &&
7100 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7101 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007102
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007103 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007104 // A multiply can be truncated by truncating its operands.
7105 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7106 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7107 NumCastsRemoved) &&
7108 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7109 NumCastsRemoved);
7110
Chris Lattner46b96052006-11-29 07:18:39 +00007111 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007112 // If we are truncating the result of this SHL, and if it's a shift of a
7113 // constant amount, we can always perform a SHL in a smaller type.
7114 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007115 uint32_t BitWidth = Ty->getBitWidth();
7116 if (BitWidth < OrigTy->getBitWidth() &&
7117 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007118 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7119 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007120 }
7121 break;
7122 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007123 // If this is a truncate of a logical shr, we can truncate it to a smaller
7124 // lshr iff we know that the bits we would otherwise be shifting in are
7125 // already zeros.
7126 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007127 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7128 uint32_t BitWidth = Ty->getBitWidth();
7129 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007130 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007131 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7132 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007133 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7134 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007135 }
7136 }
Chris Lattner46b96052006-11-29 07:18:39 +00007137 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007138 case Instruction::ZExt:
7139 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007140 case Instruction::Trunc:
7141 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007142 // can safely replace it. Note that replacing it does not reduce the number
7143 // of casts in the input.
7144 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007145 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007146
Reid Spencer3da59db2006-11-27 01:05:10 +00007147 break;
7148 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007149 // TODO: Can handle more cases here.
7150 break;
7151 }
7152
7153 return false;
7154}
7155
7156/// EvaluateInDifferentType - Given an expression that
7157/// CanEvaluateInDifferentType returns true for, actually insert the code to
7158/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007159Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007160 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007161 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007162 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007163
7164 // Otherwise, it must be an instruction.
7165 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007166 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007167 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007168 case Instruction::Add:
7169 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007170 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007171 case Instruction::And:
7172 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007173 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007174 case Instruction::AShr:
7175 case Instruction::LShr:
7176 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007177 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007178 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007179 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007180 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007181 break;
7182 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007183 case Instruction::Trunc:
7184 case Instruction::ZExt:
7185 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007186 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007187 // just return the source. There's no need to insert it because it is not
7188 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007189 if (I->getOperand(0)->getType() == Ty)
7190 return I->getOperand(0);
7191
Chris Lattner951626b2007-08-02 06:11:14 +00007192 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007193 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007194 Ty, I->getName());
7195 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007196 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007197 // TODO: Can handle more cases here.
7198 assert(0 && "Unreachable!");
7199 break;
7200 }
7201
7202 return InsertNewInstBefore(Res, *I);
7203}
7204
Reid Spencer3da59db2006-11-27 01:05:10 +00007205/// @brief Implement the transforms common to all CastInst visitors.
7206Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007207 Value *Src = CI.getOperand(0);
7208
Dan Gohman23d9d272007-05-11 21:10:54 +00007209 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007210 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007211 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007212 if (Instruction::CastOps opc =
7213 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7214 // The first cast (CSrc) is eliminable so we need to fix up or replace
7215 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007216 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007217 }
7218 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007219
Reid Spencer3da59db2006-11-27 01:05:10 +00007220 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007221 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7222 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7223 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007224
7225 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007226 if (isa<PHINode>(Src))
7227 if (Instruction *NV = FoldOpIntoPhi(CI))
7228 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007229
Reid Spencer3da59db2006-11-27 01:05:10 +00007230 return 0;
7231}
7232
Chris Lattnerd3e28342007-04-27 17:44:50 +00007233/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7234Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7235 Value *Src = CI.getOperand(0);
7236
Chris Lattnerd3e28342007-04-27 17:44:50 +00007237 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007238 // If casting the result of a getelementptr instruction with no offset, turn
7239 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007240 if (GEP->hasAllZeroIndices()) {
7241 // Changing the cast operand is usually not a good idea but it is safe
7242 // here because the pointer operand is being replaced with another
7243 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007244 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007245 CI.setOperand(0, GEP->getOperand(0));
7246 return &CI;
7247 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007248
7249 // If the GEP has a single use, and the base pointer is a bitcast, and the
7250 // GEP computes a constant offset, see if we can convert these three
7251 // instructions into fewer. This typically happens with unions and other
7252 // non-type-safe code.
7253 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7254 if (GEP->hasAllConstantIndices()) {
7255 // We are guaranteed to get a constant from EmitGEPOffset.
7256 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7257 int64_t Offset = OffsetV->getSExtValue();
7258
7259 // Get the base pointer input of the bitcast, and the type it points to.
7260 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7261 const Type *GEPIdxTy =
7262 cast<PointerType>(OrigBase->getType())->getElementType();
7263 if (GEPIdxTy->isSized()) {
7264 SmallVector<Value*, 8> NewIndices;
7265
Chris Lattnerc42e2262007-05-05 01:59:31 +00007266 // Start with the index over the outer type. Note that the type size
7267 // might be zero (even if the offset isn't zero) if the indexed type
7268 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007269 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007270 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007271 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007272 FirstIdx = Offset/TySize;
7273 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007274
Chris Lattnerc42e2262007-05-05 01:59:31 +00007275 // Handle silly modulus not returning values values [0..TySize).
7276 if (Offset < 0) {
7277 --FirstIdx;
7278 Offset += TySize;
7279 assert(Offset >= 0);
7280 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007281 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007282 }
7283
7284 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007285
7286 // Index into the types. If we fail, set OrigBase to null.
7287 while (Offset) {
7288 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7289 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007290 if (Offset < (int64_t)SL->getSizeInBytes()) {
7291 unsigned Elt = SL->getElementContainingOffset(Offset);
7292 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007293
Chris Lattner6b6aef82007-05-15 00:16:00 +00007294 Offset -= SL->getElementOffset(Elt);
7295 GEPIdxTy = STy->getElementType(Elt);
7296 } else {
7297 // Otherwise, we can't index into this, bail out.
7298 Offset = 0;
7299 OrigBase = 0;
7300 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007301 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7302 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007303 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007304 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7305 Offset %= EltSize;
7306 } else {
7307 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7308 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007309 GEPIdxTy = STy->getElementType();
7310 } else {
7311 // Otherwise, we can't index into this, bail out.
7312 Offset = 0;
7313 OrigBase = 0;
7314 }
7315 }
7316 if (OrigBase) {
7317 // If we were able to index down into an element, create the GEP
7318 // and bitcast the result. This eliminates one bitcast, potentially
7319 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007320 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7321 NewIndices.begin(),
7322 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007323 InsertNewInstBefore(NGEP, CI);
7324 NGEP->takeName(GEP);
7325
Chris Lattner9bc14642007-04-28 00:57:34 +00007326 if (isa<BitCastInst>(CI))
7327 return new BitCastInst(NGEP, CI.getType());
7328 assert(isa<PtrToIntInst>(CI));
7329 return new PtrToIntInst(NGEP, CI.getType());
7330 }
7331 }
7332 }
7333 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007334 }
7335
7336 return commonCastTransforms(CI);
7337}
7338
7339
7340
Chris Lattnerc739cd62007-03-03 05:27:34 +00007341/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7342/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007343/// cases.
7344/// @brief Implement the transforms common to CastInst with integer operands
7345Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7346 if (Instruction *Result = commonCastTransforms(CI))
7347 return Result;
7348
7349 Value *Src = CI.getOperand(0);
7350 const Type *SrcTy = Src->getType();
7351 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007352 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7353 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007354
Reid Spencer3da59db2006-11-27 01:05:10 +00007355 // See if we can simplify any instructions used by the LHS whose sole
7356 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007357 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7358 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007359 KnownZero, KnownOne))
7360 return &CI;
7361
7362 // If the source isn't an instruction or has more than one use then we
7363 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007364 Instruction *SrcI = dyn_cast<Instruction>(Src);
7365 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007366 return 0;
7367
Chris Lattnerc739cd62007-03-03 05:27:34 +00007368 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007369 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007370 if (!isa<BitCastInst>(CI) &&
7371 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007372 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007373 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007374 // eliminates the cast, so it is always a win. If this is a zero-extension,
7375 // we need to do an AND to maintain the clear top-part of the computation,
7376 // so we require that the input have eliminated at least one cast. If this
7377 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007378 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007379 bool DoXForm;
7380 switch (CI.getOpcode()) {
7381 default:
7382 // All the others use floating point so we shouldn't actually
7383 // get here because of the check above.
7384 assert(0 && "Unknown cast type");
7385 case Instruction::Trunc:
7386 DoXForm = true;
7387 break;
7388 case Instruction::ZExt:
7389 DoXForm = NumCastsRemoved >= 1;
7390 break;
7391 case Instruction::SExt:
7392 DoXForm = NumCastsRemoved >= 2;
7393 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007394 }
7395
7396 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007397 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7398 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007399 assert(Res->getType() == DestTy);
7400 switch (CI.getOpcode()) {
7401 default: assert(0 && "Unknown cast type!");
7402 case Instruction::Trunc:
7403 case Instruction::BitCast:
7404 // Just replace this cast with the result.
7405 return ReplaceInstUsesWith(CI, Res);
7406 case Instruction::ZExt: {
7407 // We need to emit an AND to clear the high bits.
7408 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007409 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7410 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007411 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007412 }
7413 case Instruction::SExt:
7414 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007415 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007416 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7417 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007418 }
7419 }
7420 }
7421
7422 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7423 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7424
7425 switch (SrcI->getOpcode()) {
7426 case Instruction::Add:
7427 case Instruction::Mul:
7428 case Instruction::And:
7429 case Instruction::Or:
7430 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007431 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007432 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7433 // Don't insert two casts if they cannot be eliminated. We allow
7434 // two casts to be inserted if the sizes are the same. This could
7435 // only be converting signedness, which is a noop.
7436 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007437 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7438 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007439 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007440 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7441 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007442 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007443 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007444 }
7445 }
7446
7447 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7448 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7449 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007450 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007451 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007452 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007453 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007454 }
7455 break;
7456 case Instruction::SDiv:
7457 case Instruction::UDiv:
7458 case Instruction::SRem:
7459 case Instruction::URem:
7460 // If we are just changing the sign, rewrite.
7461 if (DestBitSize == SrcBitSize) {
7462 // Don't insert two casts if they cannot be eliminated. We allow
7463 // two casts to be inserted if the sizes are the same. This could
7464 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007465 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7466 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007467 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7468 Op0, DestTy, SrcI);
7469 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7470 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007471 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007472 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7473 }
7474 }
7475 break;
7476
7477 case Instruction::Shl:
7478 // Allow changing the sign of the source operand. Do not allow
7479 // changing the size of the shift, UNLESS the shift amount is a
7480 // constant. We must not change variable sized shifts to a smaller
7481 // size, because it is undefined to shift more bits out than exist
7482 // in the value.
7483 if (DestBitSize == SrcBitSize ||
7484 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007485 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7486 Instruction::BitCast : Instruction::Trunc);
7487 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007488 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007489 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007490 }
7491 break;
7492 case Instruction::AShr:
7493 // If this is a signed shr, and if all bits shifted in are about to be
7494 // truncated off, turn it into an unsigned shr to allow greater
7495 // simplifications.
7496 if (DestBitSize < SrcBitSize &&
7497 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007498 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007499 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7500 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007501 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007502 }
7503 }
7504 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007505 }
7506 return 0;
7507}
7508
Chris Lattner8a9f5712007-04-11 06:57:46 +00007509Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007510 if (Instruction *Result = commonIntCastTransforms(CI))
7511 return Result;
7512
7513 Value *Src = CI.getOperand(0);
7514 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007515 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7516 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007517
7518 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7519 switch (SrcI->getOpcode()) {
7520 default: break;
7521 case Instruction::LShr:
7522 // We can shrink lshr to something smaller if we know the bits shifted in
7523 // are already zeros.
7524 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007525 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007526
7527 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007528 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007529 Value* SrcIOp0 = SrcI->getOperand(0);
7530 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007531 if (ShAmt >= DestBitWidth) // All zeros.
7532 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7533
7534 // Okay, we can shrink this. Truncate the input, then return a new
7535 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007536 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7537 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7538 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007539 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007540 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007541 } else { // This is a variable shr.
7542
7543 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7544 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7545 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007546 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007547 Value *One = ConstantInt::get(SrcI->getType(), 1);
7548
Reid Spencer832254e2007-02-02 02:16:23 +00007549 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007550 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007551 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007552 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007553 SrcI->getOperand(0),
7554 "tmp"), CI);
7555 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007556 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007557 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007558 }
7559 break;
7560 }
7561 }
7562
7563 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007564}
7565
Evan Chengb98a10e2008-03-24 00:21:34 +00007566/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7567/// in order to eliminate the icmp.
7568Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7569 bool DoXform) {
7570 // If we are just checking for a icmp eq of a single bit and zext'ing it
7571 // to an integer, then shift the bit to the appropriate place and then
7572 // cast to integer to avoid the comparison.
7573 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7574 const APInt &Op1CV = Op1C->getValue();
7575
7576 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7577 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7578 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7579 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7580 if (!DoXform) return ICI;
7581
7582 Value *In = ICI->getOperand(0);
7583 Value *Sh = ConstantInt::get(In->getType(),
7584 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007585 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007586 In->getName()+".lobit"),
7587 CI);
7588 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007589 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007590 false/*ZExt*/, "tmp", &CI);
7591
7592 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7593 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007594 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007595 In->getName()+".not"),
7596 CI);
7597 }
7598
7599 return ReplaceInstUsesWith(CI, In);
7600 }
7601
7602
7603
7604 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7605 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7606 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7607 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7608 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7609 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7610 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7611 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7612 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7613 // This only works for EQ and NE
7614 ICI->isEquality()) {
7615 // If Op1C some other power of two, convert:
7616 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7617 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7618 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7619 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7620
7621 APInt KnownZeroMask(~KnownZero);
7622 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7623 if (!DoXform) return ICI;
7624
7625 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7626 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7627 // (X&4) == 2 --> false
7628 // (X&4) != 2 --> true
7629 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7630 Res = ConstantExpr::getZExt(Res, CI.getType());
7631 return ReplaceInstUsesWith(CI, Res);
7632 }
7633
7634 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7635 Value *In = ICI->getOperand(0);
7636 if (ShiftAmt) {
7637 // Perform a logical shr by shiftamt.
7638 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007639 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007640 ConstantInt::get(In->getType(), ShiftAmt),
7641 In->getName()+".lobit"), CI);
7642 }
7643
7644 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7645 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007646 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007647 InsertNewInstBefore(cast<Instruction>(In), CI);
7648 }
7649
7650 if (CI.getType() == In->getType())
7651 return ReplaceInstUsesWith(CI, In);
7652 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007653 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007654 }
7655 }
7656 }
7657
7658 return 0;
7659}
7660
Chris Lattner8a9f5712007-04-11 06:57:46 +00007661Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007662 // If one of the common conversion will work ..
7663 if (Instruction *Result = commonIntCastTransforms(CI))
7664 return Result;
7665
7666 Value *Src = CI.getOperand(0);
7667
7668 // If this is a cast of a cast
7669 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007670 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7671 // types and if the sizes are just right we can convert this into a logical
7672 // 'and' which will be much cheaper than the pair of casts.
7673 if (isa<TruncInst>(CSrc)) {
7674 // Get the sizes of the types involved
7675 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007676 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7677 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7678 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007679 // If we're actually extending zero bits and the trunc is a no-op
7680 if (MidSize < DstSize && SrcSize == DstSize) {
7681 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007682 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007683 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007684 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007685 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007686 // Unfortunately, if the type changed, we need to cast it back.
7687 if (And->getType() != CI.getType()) {
7688 And->setName(CSrc->getName()+".mask");
7689 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007690 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007691 }
7692 return And;
7693 }
7694 }
7695 }
7696
Evan Chengb98a10e2008-03-24 00:21:34 +00007697 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7698 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007699
Evan Chengb98a10e2008-03-24 00:21:34 +00007700 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7701 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7702 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7703 // of the (zext icmp) will be transformed.
7704 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7705 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7706 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7707 (transformZExtICmp(LHS, CI, false) ||
7708 transformZExtICmp(RHS, CI, false))) {
7709 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7710 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007711 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007712 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007713 }
7714
Reid Spencer3da59db2006-11-27 01:05:10 +00007715 return 0;
7716}
7717
Chris Lattner8a9f5712007-04-11 06:57:46 +00007718Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007719 if (Instruction *I = commonIntCastTransforms(CI))
7720 return I;
7721
Chris Lattner8a9f5712007-04-11 06:57:46 +00007722 Value *Src = CI.getOperand(0);
7723
7724 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7725 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7726 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7727 // If we are just checking for a icmp eq of a single bit and zext'ing it
7728 // to an integer, then shift the bit to the appropriate place and then
7729 // cast to integer to avoid the comparison.
7730 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7731 const APInt &Op1CV = Op1C->getValue();
7732
7733 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7734 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7735 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7736 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7737 Value *In = ICI->getOperand(0);
7738 Value *Sh = ConstantInt::get(In->getType(),
7739 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007740 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007741 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007742 CI);
7743 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007744 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007745 true/*SExt*/, "tmp", &CI);
7746
7747 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007748 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007749 In->getName()+".not"), CI);
7750
7751 return ReplaceInstUsesWith(CI, In);
7752 }
7753 }
7754 }
7755
Chris Lattnerba417832007-04-11 06:12:58 +00007756 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007757}
7758
Chris Lattnerb7530652008-01-27 05:29:54 +00007759/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7760/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007761static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007762 APFloat F = CFP->getValueAPF();
7763 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007764 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007765 return 0;
7766}
7767
7768/// LookThroughFPExtensions - If this is an fp extension instruction, look
7769/// through it until we get the source value.
7770static Value *LookThroughFPExtensions(Value *V) {
7771 if (Instruction *I = dyn_cast<Instruction>(V))
7772 if (I->getOpcode() == Instruction::FPExt)
7773 return LookThroughFPExtensions(I->getOperand(0));
7774
7775 // If this value is a constant, return the constant in the smallest FP type
7776 // that can accurately represent it. This allows us to turn
7777 // (float)((double)X+2.0) into x+2.0f.
7778 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7779 if (CFP->getType() == Type::PPC_FP128Ty)
7780 return V; // No constant folding of this.
7781 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007782 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007783 return V;
7784 if (CFP->getType() == Type::DoubleTy)
7785 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007786 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007787 return V;
7788 // Don't try to shrink to various long double types.
7789 }
7790
7791 return V;
7792}
7793
7794Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7795 if (Instruction *I = commonCastTransforms(CI))
7796 return I;
7797
7798 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7799 // smaller than the destination type, we can eliminate the truncate by doing
7800 // the add as the smaller type. This applies to add/sub/mul/div as well as
7801 // many builtins (sqrt, etc).
7802 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7803 if (OpI && OpI->hasOneUse()) {
7804 switch (OpI->getOpcode()) {
7805 default: break;
7806 case Instruction::Add:
7807 case Instruction::Sub:
7808 case Instruction::Mul:
7809 case Instruction::FDiv:
7810 case Instruction::FRem:
7811 const Type *SrcTy = OpI->getType();
7812 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7813 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7814 if (LHSTrunc->getType() != SrcTy &&
7815 RHSTrunc->getType() != SrcTy) {
7816 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7817 // If the source types were both smaller than the destination type of
7818 // the cast, do this xform.
7819 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7820 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7821 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7822 CI.getType(), CI);
7823 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7824 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007825 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007826 }
7827 }
7828 break;
7829 }
7830 }
7831 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007832}
7833
7834Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7835 return commonCastTransforms(CI);
7836}
7837
7838Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007839 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007840}
7841
7842Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007843 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007844}
7845
7846Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7847 return commonCastTransforms(CI);
7848}
7849
7850Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7851 return commonCastTransforms(CI);
7852}
7853
7854Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007855 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007856}
7857
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007858Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7859 if (Instruction *I = commonCastTransforms(CI))
7860 return I;
7861
7862 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7863 if (!DestPointee->isSized()) return 0;
7864
7865 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7866 ConstantInt *Cst;
7867 Value *X;
7868 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7869 m_ConstantInt(Cst)))) {
7870 // If the source and destination operands have the same type, see if this
7871 // is a single-index GEP.
7872 if (X->getType() == CI.getType()) {
7873 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007874 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007875
7876 // Convert the constant to intptr type.
7877 APInt Offset = Cst->getValue();
7878 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7879
7880 // If Offset is evenly divisible by Size, we can do this xform.
7881 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7882 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007883 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007884 }
7885 }
7886 // TODO: Could handle other cases, e.g. where add is indexing into field of
7887 // struct etc.
7888 } else if (CI.getOperand(0)->hasOneUse() &&
7889 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7890 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7891 // "inttoptr+GEP" instead of "add+intptr".
7892
7893 // Get the size of the pointee type.
7894 uint64_t Size = TD->getABITypeSize(DestPointee);
7895
7896 // Convert the constant to intptr type.
7897 APInt Offset = Cst->getValue();
7898 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7899
7900 // If Offset is evenly divisible by Size, we can do this xform.
7901 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7902 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7903
7904 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7905 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007906 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007907 }
7908 }
7909 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007910}
7911
Chris Lattnerd3e28342007-04-27 17:44:50 +00007912Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007913 // If the operands are integer typed then apply the integer transforms,
7914 // otherwise just apply the common ones.
7915 Value *Src = CI.getOperand(0);
7916 const Type *SrcTy = Src->getType();
7917 const Type *DestTy = CI.getType();
7918
Chris Lattner42a75512007-01-15 02:27:26 +00007919 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007920 if (Instruction *Result = commonIntCastTransforms(CI))
7921 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007922 } else if (isa<PointerType>(SrcTy)) {
7923 if (Instruction *I = commonPointerCastTransforms(CI))
7924 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007925 } else {
7926 if (Instruction *Result = commonCastTransforms(CI))
7927 return Result;
7928 }
7929
7930
7931 // Get rid of casts from one type to the same type. These are useless and can
7932 // be replaced by the operand.
7933 if (DestTy == Src->getType())
7934 return ReplaceInstUsesWith(CI, Src);
7935
Reid Spencer3da59db2006-11-27 01:05:10 +00007936 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007937 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7938 const Type *DstElTy = DstPTy->getElementType();
7939 const Type *SrcElTy = SrcPTy->getElementType();
7940
Nate Begeman83ad90a2008-03-31 00:22:16 +00007941 // If the address spaces don't match, don't eliminate the bitcast, which is
7942 // required for changing types.
7943 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7944 return 0;
7945
Chris Lattnerd3e28342007-04-27 17:44:50 +00007946 // If we are casting a malloc or alloca to a pointer to a type of the same
7947 // size, rewrite the allocation instruction to allocate the "right" type.
7948 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7949 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7950 return V;
7951
Chris Lattnerd717c182007-05-05 22:32:24 +00007952 // If the source and destination are pointers, and this cast is equivalent
7953 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007954 // This can enhance SROA and other transforms that want type-safe pointers.
7955 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7956 unsigned NumZeros = 0;
7957 while (SrcElTy != DstElTy &&
7958 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7959 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7960 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7961 ++NumZeros;
7962 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007963
Chris Lattnerd3e28342007-04-27 17:44:50 +00007964 // If we found a path from the src to dest, create the getelementptr now.
7965 if (SrcElTy == DstElTy) {
7966 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007967 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7968 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007969 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007970 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007971
Reid Spencer3da59db2006-11-27 01:05:10 +00007972 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7973 if (SVI->hasOneUse()) {
7974 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7975 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007976 if (isa<VectorType>(DestTy) &&
7977 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007978 SVI->getType()->getNumElements()) {
7979 CastInst *Tmp;
7980 // If either of the operands is a cast from CI.getType(), then
7981 // evaluating the shuffle in the casted destination's type will allow
7982 // us to eliminate at least one cast.
7983 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7984 Tmp->getOperand(0)->getType() == DestTy) ||
7985 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7986 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007987 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7988 SVI->getOperand(0), DestTy, &CI);
7989 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7990 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007991 // Return a new shuffle vector. Use the same element ID's, as we
7992 // know the vector types match #elts.
7993 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007994 }
7995 }
7996 }
7997 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007998 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007999}
8000
Chris Lattnere576b912004-04-09 23:46:01 +00008001/// GetSelectFoldableOperands - We want to turn code that looks like this:
8002/// %C = or %A, %B
8003/// %D = select %cond, %C, %A
8004/// into:
8005/// %C = select %cond, %B, 0
8006/// %D = or %A, %C
8007///
8008/// Assuming that the specified instruction is an operand to the select, return
8009/// a bitmask indicating which operands of this instruction are foldable if they
8010/// equal the other incoming value of the select.
8011///
8012static unsigned GetSelectFoldableOperands(Instruction *I) {
8013 switch (I->getOpcode()) {
8014 case Instruction::Add:
8015 case Instruction::Mul:
8016 case Instruction::And:
8017 case Instruction::Or:
8018 case Instruction::Xor:
8019 return 3; // Can fold through either operand.
8020 case Instruction::Sub: // Can only fold on the amount subtracted.
8021 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008022 case Instruction::LShr:
8023 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008024 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008025 default:
8026 return 0; // Cannot fold
8027 }
8028}
8029
8030/// GetSelectFoldableConstant - For the same transformation as the previous
8031/// function, return the identity constant that goes into the select.
8032static Constant *GetSelectFoldableConstant(Instruction *I) {
8033 switch (I->getOpcode()) {
8034 default: assert(0 && "This cannot happen!"); abort();
8035 case Instruction::Add:
8036 case Instruction::Sub:
8037 case Instruction::Or:
8038 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008039 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008040 case Instruction::LShr:
8041 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008042 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008043 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008044 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008045 case Instruction::Mul:
8046 return ConstantInt::get(I->getType(), 1);
8047 }
8048}
8049
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008050/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8051/// have the same opcode and only one use each. Try to simplify this.
8052Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8053 Instruction *FI) {
8054 if (TI->getNumOperands() == 1) {
8055 // If this is a non-volatile load or a cast from the same type,
8056 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008057 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008058 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8059 return 0;
8060 } else {
8061 return 0; // unknown unary op.
8062 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008063
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008064 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008065 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8066 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008067 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008068 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008069 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008070 }
8071
Reid Spencer832254e2007-02-02 02:16:23 +00008072 // Only handle binary operators here.
8073 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008074 return 0;
8075
8076 // Figure out if the operations have any operands in common.
8077 Value *MatchOp, *OtherOpT, *OtherOpF;
8078 bool MatchIsOpZero;
8079 if (TI->getOperand(0) == FI->getOperand(0)) {
8080 MatchOp = TI->getOperand(0);
8081 OtherOpT = TI->getOperand(1);
8082 OtherOpF = FI->getOperand(1);
8083 MatchIsOpZero = true;
8084 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8085 MatchOp = TI->getOperand(1);
8086 OtherOpT = TI->getOperand(0);
8087 OtherOpF = FI->getOperand(0);
8088 MatchIsOpZero = false;
8089 } else if (!TI->isCommutative()) {
8090 return 0;
8091 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8092 MatchOp = TI->getOperand(0);
8093 OtherOpT = TI->getOperand(1);
8094 OtherOpF = FI->getOperand(0);
8095 MatchIsOpZero = true;
8096 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8097 MatchOp = TI->getOperand(1);
8098 OtherOpT = TI->getOperand(0);
8099 OtherOpF = FI->getOperand(1);
8100 MatchIsOpZero = true;
8101 } else {
8102 return 0;
8103 }
8104
8105 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008106 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8107 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008108 InsertNewInstBefore(NewSI, SI);
8109
8110 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8111 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008112 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008113 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008114 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008115 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008116 assert(0 && "Shouldn't get here");
8117 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008118}
8119
Chris Lattner3d69f462004-03-12 05:52:32 +00008120Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008121 Value *CondVal = SI.getCondition();
8122 Value *TrueVal = SI.getTrueValue();
8123 Value *FalseVal = SI.getFalseValue();
8124
8125 // select true, X, Y -> X
8126 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008127 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008128 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008129
8130 // select C, X, X -> X
8131 if (TrueVal == FalseVal)
8132 return ReplaceInstUsesWith(SI, TrueVal);
8133
Chris Lattnere87597f2004-10-16 18:11:37 +00008134 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8135 return ReplaceInstUsesWith(SI, FalseVal);
8136 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8137 return ReplaceInstUsesWith(SI, TrueVal);
8138 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8139 if (isa<Constant>(TrueVal))
8140 return ReplaceInstUsesWith(SI, TrueVal);
8141 else
8142 return ReplaceInstUsesWith(SI, FalseVal);
8143 }
8144
Reid Spencer4fe16d62007-01-11 18:21:29 +00008145 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008146 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008147 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008148 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008149 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008150 } else {
8151 // Change: A = select B, false, C --> A = and !B, C
8152 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008153 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008154 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008155 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008156 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008157 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008158 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008159 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008160 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008161 } else {
8162 // Change: A = select B, C, true --> A = or !B, C
8163 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008164 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008165 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008166 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008167 }
8168 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008169
8170 // select a, b, a -> a&b
8171 // select a, a, b -> a|b
8172 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008173 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008174 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008175 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008176 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008177
Chris Lattner2eefe512004-04-09 19:05:30 +00008178 // Selecting between two integer constants?
8179 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8180 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008181 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008182 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008183 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008184 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008185 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008186 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008187 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008188 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008189 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008190 }
Chris Lattnerba417832007-04-11 06:12:58 +00008191
8192 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008193
Reid Spencere4d87aa2006-12-23 06:05:41 +00008194 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008195
Reid Spencere4d87aa2006-12-23 06:05:41 +00008196 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008197 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008198 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008199 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008200 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008201 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008202 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008203 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008204 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008205 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008206 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008207 InsertNewInstBefore(SRA, SI);
8208
Reid Spencer3da59db2006-11-27 01:05:10 +00008209 // Finally, convert to the type of the select RHS. We figure out
8210 // if this requires a SExt, Trunc or BitCast based on the sizes.
8211 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008212 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8213 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008214 if (SRASize < SISize)
8215 opc = Instruction::SExt;
8216 else if (SRASize > SISize)
8217 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008218 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008219 }
8220 }
8221
8222
8223 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008224 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008225 // non-constant value, eliminate this whole mess. This corresponds to
8226 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008227 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008228 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008229 cast<Constant>(IC->getOperand(1))->isNullValue())
8230 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8231 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008232 isa<ConstantInt>(ICA->getOperand(1)) &&
8233 (ICA->getOperand(1) == TrueValC ||
8234 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008235 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8236 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008237 // know whether we have a icmp_ne or icmp_eq and whether the
8238 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008239 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008240 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008241 Value *V = ICA;
8242 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008243 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008244 Instruction::Xor, V, ICA->getOperand(1)), SI);
8245 return ReplaceInstUsesWith(SI, V);
8246 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008247 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008248 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008249
8250 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008251 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8252 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008253 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008254 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8255 // This is not safe in general for floating point:
8256 // consider X== -0, Y== +0.
8257 // It becomes safe if either operand is a nonzero constant.
8258 ConstantFP *CFPt, *CFPf;
8259 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8260 !CFPt->getValueAPF().isZero()) ||
8261 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8262 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008263 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008264 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008265 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008266 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008267 return ReplaceInstUsesWith(SI, TrueVal);
8268 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8269
Reid Spencere4d87aa2006-12-23 06:05:41 +00008270 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008271 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008272 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8273 // This is not safe in general for floating point:
8274 // consider X== -0, Y== +0.
8275 // It becomes safe if either operand is a nonzero constant.
8276 ConstantFP *CFPt, *CFPf;
8277 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8278 !CFPt->getValueAPF().isZero()) ||
8279 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8280 !CFPf->getValueAPF().isZero()))
8281 return ReplaceInstUsesWith(SI, FalseVal);
8282 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008283 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008284 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8285 return ReplaceInstUsesWith(SI, TrueVal);
8286 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8287 }
8288 }
8289
8290 // See if we are selecting two values based on a comparison of the two values.
8291 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8292 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8293 // Transform (X == Y) ? X : Y -> Y
8294 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8295 return ReplaceInstUsesWith(SI, FalseVal);
8296 // Transform (X != Y) ? X : Y -> X
8297 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8298 return ReplaceInstUsesWith(SI, TrueVal);
8299 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8300
8301 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8302 // Transform (X == Y) ? Y : X -> X
8303 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8304 return ReplaceInstUsesWith(SI, FalseVal);
8305 // Transform (X != Y) ? Y : X -> Y
8306 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008307 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008308 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8309 }
8310 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008311
Chris Lattner87875da2005-01-13 22:52:24 +00008312 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8313 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8314 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008315 Instruction *AddOp = 0, *SubOp = 0;
8316
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008317 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8318 if (TI->getOpcode() == FI->getOpcode())
8319 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8320 return IV;
8321
8322 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8323 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008324 if (TI->getOpcode() == Instruction::Sub &&
8325 FI->getOpcode() == Instruction::Add) {
8326 AddOp = FI; SubOp = TI;
8327 } else if (FI->getOpcode() == Instruction::Sub &&
8328 TI->getOpcode() == Instruction::Add) {
8329 AddOp = TI; SubOp = FI;
8330 }
8331
8332 if (AddOp) {
8333 Value *OtherAddOp = 0;
8334 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8335 OtherAddOp = AddOp->getOperand(1);
8336 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8337 OtherAddOp = AddOp->getOperand(0);
8338 }
8339
8340 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008341 // So at this point we know we have (Y -> OtherAddOp):
8342 // select C, (add X, Y), (sub X, Z)
8343 Value *NegVal; // Compute -Z
8344 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8345 NegVal = ConstantExpr::getNeg(C);
8346 } else {
8347 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008348 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008349 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008350
8351 Value *NewTrueOp = OtherAddOp;
8352 Value *NewFalseOp = NegVal;
8353 if (AddOp != TI)
8354 std::swap(NewTrueOp, NewFalseOp);
8355 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008356 SelectInst::Create(CondVal, NewTrueOp,
8357 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008358
8359 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008360 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008361 }
8362 }
8363 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008364
Chris Lattnere576b912004-04-09 23:46:01 +00008365 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008366 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008367 // See the comment above GetSelectFoldableOperands for a description of the
8368 // transformation we are doing here.
8369 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8370 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8371 !isa<Constant>(FalseVal))
8372 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8373 unsigned OpToFold = 0;
8374 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8375 OpToFold = 1;
8376 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8377 OpToFold = 2;
8378 }
8379
8380 if (OpToFold) {
8381 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008382 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008383 SelectInst::Create(SI.getCondition(),
8384 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008385 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008386 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008387 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008388 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008389 else {
8390 assert(0 && "Unknown instruction!!");
8391 }
8392 }
8393 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008394
Chris Lattnere576b912004-04-09 23:46:01 +00008395 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8396 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8397 !isa<Constant>(TrueVal))
8398 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8399 unsigned OpToFold = 0;
8400 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8401 OpToFold = 1;
8402 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8403 OpToFold = 2;
8404 }
8405
8406 if (OpToFold) {
8407 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008408 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008409 SelectInst::Create(SI.getCondition(), C,
8410 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008411 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008412 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008413 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008414 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008415 else
Chris Lattnere576b912004-04-09 23:46:01 +00008416 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008417 }
8418 }
8419 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008420
8421 if (BinaryOperator::isNot(CondVal)) {
8422 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8423 SI.setOperand(1, FalseVal);
8424 SI.setOperand(2, TrueVal);
8425 return &SI;
8426 }
8427
Chris Lattner3d69f462004-03-12 05:52:32 +00008428 return 0;
8429}
8430
Dan Gohmaneee962e2008-04-10 18:43:06 +00008431/// EnforceKnownAlignment - If the specified pointer points to an object that
8432/// we control, modify the object's alignment to PrefAlign. This isn't
8433/// often possible though. If alignment is important, a more reliable approach
8434/// is to simply align all global variables and allocation instructions to
8435/// their preferred alignment from the beginning.
8436///
8437static unsigned EnforceKnownAlignment(Value *V,
8438 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008439
Dan Gohmaneee962e2008-04-10 18:43:06 +00008440 User *U = dyn_cast<User>(V);
8441 if (!U) return Align;
8442
8443 switch (getOpcode(U)) {
8444 default: break;
8445 case Instruction::BitCast:
8446 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8447 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008448 // If all indexes are zero, it is just the alignment of the base pointer.
8449 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008450 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8451 if (!isa<Constant>(U->getOperand(i)) ||
8452 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008453 AllZeroOperands = false;
8454 break;
8455 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008456
8457 if (AllZeroOperands) {
8458 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008459 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008460 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008461 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008462 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008463 }
8464
8465 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8466 // If there is a large requested alignment and we can, bump up the alignment
8467 // of the global.
8468 if (!GV->isDeclaration()) {
8469 GV->setAlignment(PrefAlign);
8470 Align = PrefAlign;
8471 }
8472 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8473 // If there is a requested alignment and if this is an alloca, round up. We
8474 // don't do this for malloc, because some systems can't respect the request.
8475 if (isa<AllocaInst>(AI)) {
8476 AI->setAlignment(PrefAlign);
8477 Align = PrefAlign;
8478 }
8479 }
8480
8481 return Align;
8482}
8483
8484/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8485/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8486/// and it is more than the alignment of the ultimate object, see if we can
8487/// increase the alignment of the ultimate object, making this check succeed.
8488unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8489 unsigned PrefAlign) {
8490 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8491 sizeof(PrefAlign) * CHAR_BIT;
8492 APInt Mask = APInt::getAllOnesValue(BitWidth);
8493 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8494 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8495 unsigned TrailZ = KnownZero.countTrailingOnes();
8496 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8497
8498 if (PrefAlign > Align)
8499 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8500
8501 // We don't need to make any adjustment.
8502 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008503}
8504
Chris Lattnerf497b022008-01-13 23:50:23 +00008505Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008506 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8507 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008508 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8509 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8510
8511 if (CopyAlign < MinAlign) {
8512 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8513 return MI;
8514 }
8515
8516 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8517 // load/store.
8518 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8519 if (MemOpLength == 0) return 0;
8520
Chris Lattner37ac6082008-01-14 00:28:35 +00008521 // Source and destination pointer types are always "i8*" for intrinsic. See
8522 // if the size is something we can handle with a single primitive load/store.
8523 // A single load+store correctly handles overlapping memory in the memmove
8524 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008525 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008526 if (Size == 0) return MI; // Delete this mem transfer.
8527
8528 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008529 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008530
Chris Lattner37ac6082008-01-14 00:28:35 +00008531 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008532 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008533
8534 // Memcpy forces the use of i8* for the source and destination. That means
8535 // that if you're using memcpy to move one double around, you'll get a cast
8536 // from double* to i8*. We'd much rather use a double load+store rather than
8537 // an i64 load+store, here because this improves the odds that the source or
8538 // dest address will be promotable. See if we can find a better type than the
8539 // integer datatype.
8540 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8541 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8542 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8543 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8544 // down through these levels if so.
8545 while (!SrcETy->isFirstClassType()) {
8546 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8547 if (STy->getNumElements() == 1)
8548 SrcETy = STy->getElementType(0);
8549 else
8550 break;
8551 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8552 if (ATy->getNumElements() == 1)
8553 SrcETy = ATy->getElementType();
8554 else
8555 break;
8556 } else
8557 break;
8558 }
8559
8560 if (SrcETy->isFirstClassType())
8561 NewPtrTy = PointerType::getUnqual(SrcETy);
8562 }
8563 }
8564
8565
Chris Lattnerf497b022008-01-13 23:50:23 +00008566 // If the memcpy/memmove provides better alignment info than we can
8567 // infer, use it.
8568 SrcAlign = std::max(SrcAlign, CopyAlign);
8569 DstAlign = std::max(DstAlign, CopyAlign);
8570
8571 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8572 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008573 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8574 InsertNewInstBefore(L, *MI);
8575 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8576
8577 // Set the size of the copy to 0, it will be deleted on the next iteration.
8578 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8579 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008580}
Chris Lattner3d69f462004-03-12 05:52:32 +00008581
Chris Lattner69ea9d22008-04-30 06:39:11 +00008582Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8583 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8584 if (MI->getAlignment()->getZExtValue() < Alignment) {
8585 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8586 return MI;
8587 }
8588
8589 // Extract the length and alignment and fill if they are constant.
8590 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8591 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8592 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8593 return 0;
8594 uint64_t Len = LenC->getZExtValue();
8595 Alignment = MI->getAlignment()->getZExtValue();
8596
8597 // If the length is zero, this is a no-op
8598 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8599
8600 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8601 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8602 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8603
8604 Value *Dest = MI->getDest();
8605 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8606
8607 // Alignment 0 is identity for alignment 1 for memset, but not store.
8608 if (Alignment == 0) Alignment = 1;
8609
8610 // Extract the fill value and store.
8611 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8612 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8613 Alignment), *MI);
8614
8615 // Set the size of the copy to 0, it will be deleted on the next iteration.
8616 MI->setLength(Constant::getNullValue(LenC->getType()));
8617 return MI;
8618 }
8619
8620 return 0;
8621}
8622
8623
Chris Lattner8b0ea312006-01-13 20:11:04 +00008624/// visitCallInst - CallInst simplification. This mostly only handles folding
8625/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8626/// the heavy lifting.
8627///
Chris Lattner9fe38862003-06-19 17:00:31 +00008628Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008629 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8630 if (!II) return visitCallSite(&CI);
8631
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008632 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8633 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008634 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008635 bool Changed = false;
8636
8637 // memmove/cpy/set of zero bytes is a noop.
8638 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8639 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8640
Chris Lattner35b9e482004-10-12 04:52:52 +00008641 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008642 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008643 // Replace the instruction with just byte operations. We would
8644 // transform other cases to loads/stores, but we don't know if
8645 // alignment is sufficient.
8646 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008647 }
8648
Chris Lattner35b9e482004-10-12 04:52:52 +00008649 // If we have a memmove and the source operation is a constant global,
8650 // then the source and dest pointers can't alias, so we can change this
8651 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008652 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008653 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8654 if (GVSrc->isConstant()) {
8655 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008656 Intrinsic::ID MemCpyID;
8657 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8658 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008659 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008660 MemCpyID = Intrinsic::memcpy_i64;
8661 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008662 Changed = true;
8663 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008664 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008665
Chris Lattner95a959d2006-03-06 20:18:44 +00008666 // If we can determine a pointer alignment that is bigger than currently
8667 // set, update the alignment.
8668 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008669 if (Instruction *I = SimplifyMemTransfer(MI))
8670 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008671 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8672 if (Instruction *I = SimplifyMemSet(MSI))
8673 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008674 }
8675
Chris Lattner8b0ea312006-01-13 20:11:04 +00008676 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008677 } else {
8678 switch (II->getIntrinsicID()) {
8679 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008680 case Intrinsic::ppc_altivec_lvx:
8681 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008682 case Intrinsic::x86_sse_loadu_ps:
8683 case Intrinsic::x86_sse2_loadu_pd:
8684 case Intrinsic::x86_sse2_loadu_dq:
8685 // Turn PPC lvx -> load if the pointer is known aligned.
8686 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008687 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008688 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8689 PointerType::getUnqual(II->getType()),
8690 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008691 return new LoadInst(Ptr);
8692 }
8693 break;
8694 case Intrinsic::ppc_altivec_stvx:
8695 case Intrinsic::ppc_altivec_stvxl:
8696 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008697 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008698 const Type *OpPtrTy =
8699 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008700 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008701 return new StoreInst(II->getOperand(1), Ptr);
8702 }
8703 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008704 case Intrinsic::x86_sse_storeu_ps:
8705 case Intrinsic::x86_sse2_storeu_pd:
8706 case Intrinsic::x86_sse2_storeu_dq:
8707 case Intrinsic::x86_sse2_storel_dq:
8708 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008709 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008710 const Type *OpPtrTy =
8711 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008712 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008713 return new StoreInst(II->getOperand(2), Ptr);
8714 }
8715 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008716
8717 case Intrinsic::x86_sse_cvttss2si: {
8718 // These intrinsics only demands the 0th element of its input vector. If
8719 // we can simplify the input based on that, do so now.
8720 uint64_t UndefElts;
8721 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8722 UndefElts)) {
8723 II->setOperand(1, V);
8724 return II;
8725 }
8726 break;
8727 }
8728
Chris Lattnere2ed0572006-04-06 19:19:17 +00008729 case Intrinsic::ppc_altivec_vperm:
8730 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008731 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008732 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8733
8734 // Check that all of the elements are integer constants or undefs.
8735 bool AllEltsOk = true;
8736 for (unsigned i = 0; i != 16; ++i) {
8737 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8738 !isa<UndefValue>(Mask->getOperand(i))) {
8739 AllEltsOk = false;
8740 break;
8741 }
8742 }
8743
8744 if (AllEltsOk) {
8745 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008746 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8747 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008748 Value *Result = UndefValue::get(Op0->getType());
8749
8750 // Only extract each element once.
8751 Value *ExtractedElts[32];
8752 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8753
8754 for (unsigned i = 0; i != 16; ++i) {
8755 if (isa<UndefValue>(Mask->getOperand(i)))
8756 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008757 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008758 Idx &= 31; // Match the hardware behavior.
8759
8760 if (ExtractedElts[Idx] == 0) {
8761 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008762 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008763 InsertNewInstBefore(Elt, CI);
8764 ExtractedElts[Idx] = Elt;
8765 }
8766
8767 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008768 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8769 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008770 InsertNewInstBefore(cast<Instruction>(Result), CI);
8771 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008772 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008773 }
8774 }
8775 break;
8776
Chris Lattnera728ddc2006-01-13 21:28:09 +00008777 case Intrinsic::stackrestore: {
8778 // If the save is right next to the restore, remove the restore. This can
8779 // happen when variable allocas are DCE'd.
8780 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8781 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8782 BasicBlock::iterator BI = SS;
8783 if (&*++BI == II)
8784 return EraseInstFromFunction(CI);
8785 }
8786 }
8787
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008788 // Scan down this block to see if there is another stack restore in the
8789 // same block without an intervening call/alloca.
8790 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008791 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008792 bool CannotRemove = false;
8793 for (++BI; &*BI != TI; ++BI) {
8794 if (isa<AllocaInst>(BI)) {
8795 CannotRemove = true;
8796 break;
8797 }
8798 if (isa<CallInst>(BI)) {
8799 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008800 CannotRemove = true;
8801 break;
8802 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008803 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008804 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008805 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008806 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008807
8808 // If the stack restore is in a return/unwind block and if there are no
8809 // allocas or calls between the restore and the return, nuke the restore.
8810 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8811 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008812 break;
8813 }
8814 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008815 }
8816
Chris Lattner8b0ea312006-01-13 20:11:04 +00008817 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008818}
8819
8820// InvokeInst simplification
8821//
8822Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008823 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008824}
8825
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008826/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8827/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008828static bool isSafeToEliminateVarargsCast(const CallSite CS,
8829 const CastInst * const CI,
8830 const TargetData * const TD,
8831 const int ix) {
8832 if (!CI->isLosslessCast())
8833 return false;
8834
8835 // The size of ByVal arguments is derived from the type, so we
8836 // can't change to a type with a different size. If the size were
8837 // passed explicitly we could avoid this check.
8838 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8839 return true;
8840
8841 const Type* SrcTy =
8842 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8843 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8844 if (!SrcTy->isSized() || !DstTy->isSized())
8845 return false;
8846 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8847 return false;
8848 return true;
8849}
8850
Chris Lattnera44d8a22003-10-07 22:32:43 +00008851// visitCallSite - Improvements for call and invoke instructions.
8852//
8853Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008854 bool Changed = false;
8855
8856 // If the callee is a constexpr cast of a function, attempt to move the cast
8857 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008858 if (transformConstExprCastCall(CS)) return 0;
8859
Chris Lattner6c266db2003-10-07 22:54:13 +00008860 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008861
Chris Lattner08b22ec2005-05-13 07:09:09 +00008862 if (Function *CalleeF = dyn_cast<Function>(Callee))
8863 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8864 Instruction *OldCall = CS.getInstruction();
8865 // If the call and callee calling conventions don't match, this call must
8866 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008867 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008868 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8869 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008870 if (!OldCall->use_empty())
8871 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8872 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8873 return EraseInstFromFunction(*OldCall);
8874 return 0;
8875 }
8876
Chris Lattner17be6352004-10-18 02:59:09 +00008877 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8878 // This instruction is not reachable, just remove it. We insert a store to
8879 // undef so that we know that this code is not reachable, despite the fact
8880 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008881 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008882 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008883 CS.getInstruction());
8884
8885 if (!CS.getInstruction()->use_empty())
8886 CS.getInstruction()->
8887 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8888
8889 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8890 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008891 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8892 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008893 }
Chris Lattner17be6352004-10-18 02:59:09 +00008894 return EraseInstFromFunction(*CS.getInstruction());
8895 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008896
Duncan Sandscdb6d922007-09-17 10:26:40 +00008897 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8898 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8899 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8900 return transformCallThroughTrampoline(CS);
8901
Chris Lattner6c266db2003-10-07 22:54:13 +00008902 const PointerType *PTy = cast<PointerType>(Callee->getType());
8903 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8904 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00008905 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00008906 // See if we can optimize any arguments passed through the varargs area of
8907 // the call.
8908 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00008909 E = CS.arg_end(); I != E; ++I, ++ix) {
8910 CastInst *CI = dyn_cast<CastInst>(*I);
8911 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8912 *I = CI->getOperand(0);
8913 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00008914 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00008915 }
Chris Lattner6c266db2003-10-07 22:54:13 +00008916 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008917
Duncan Sandsf0c33542007-12-19 21:13:37 +00008918 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008919 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008920 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008921 Changed = true;
8922 }
8923
Chris Lattner6c266db2003-10-07 22:54:13 +00008924 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008925}
8926
Chris Lattner9fe38862003-06-19 17:00:31 +00008927// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8928// attempt to move the cast to the arguments of the call/invoke.
8929//
8930bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8931 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8932 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008933 if (CE->getOpcode() != Instruction::BitCast ||
8934 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008935 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008936 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008937 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008938 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008939
8940 // Okay, this is a cast from a function to a different type. Unless doing so
8941 // would cause a type conversion of one of our arguments, change this call to
8942 // be a direct call with arguments casted to the appropriate types.
8943 //
8944 const FunctionType *FT = Callee->getFunctionType();
8945 const Type *OldRetTy = Caller->getType();
8946
Devang Patel75e6f022008-03-11 18:04:06 +00008947 if (isa<StructType>(FT->getReturnType()))
8948 return false; // TODO: Handle multiple return values.
8949
Chris Lattnerf78616b2004-01-14 06:06:08 +00008950 // Check to see if we are changing the return type...
8951 if (OldRetTy != FT->getReturnType()) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00008952 if (Callee->isDeclaration() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008953 // Conversion is ok if changing from pointer to int of same size.
8954 !(isa<PointerType>(FT->getReturnType()) &&
8955 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008956 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008957
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008958 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008959 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008960 FT->getReturnType() != Type::VoidTy &&
8961 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008962 return false; // Cannot transform this return value.
8963
Chris Lattner58d74912008-03-12 17:45:29 +00008964 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8965 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008966 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8967 return false; // Attribute not compatible with transformed value.
8968 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008969
Chris Lattnerf78616b2004-01-14 06:06:08 +00008970 // If the callsite is an invoke instruction, and the return value is used by
8971 // a PHI node in a successor, we cannot change the return type of the call
8972 // because there is no place to put the cast instruction (without breaking
8973 // the critical edge). Bail out in this case.
8974 if (!Caller->use_empty())
8975 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8976 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8977 UI != E; ++UI)
8978 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8979 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008980 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008981 return false;
8982 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008983
8984 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8985 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008986
Chris Lattner9fe38862003-06-19 17:00:31 +00008987 CallSite::arg_iterator AI = CS.arg_begin();
8988 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8989 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008990 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008991
8992 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008993 return false; // Cannot transform this parameter value.
8994
Chris Lattner58d74912008-03-12 17:45:29 +00008995 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8996 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008997
Reid Spencer3da59db2006-11-27 01:05:10 +00008998 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008999 // Some conversions are safe even if we do not have a body.
9000 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00009001 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00009002 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00009003 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009004 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9005 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00009006 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00009007 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009008 }
9009
9010 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009011 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009012 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009013
Chris Lattner58d74912008-03-12 17:45:29 +00009014 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9015 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009016 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009017 // won't be dropping them. Check that these extra arguments have attributes
9018 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009019 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9020 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009021 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009022 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009023 if (PAttrs & ParamAttr::VarArgsIncompatible)
9024 return false;
9025 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009026
Chris Lattner9fe38862003-06-19 17:00:31 +00009027 // Okay, we decided that this is a safe thing to do: go ahead and start
9028 // inserting cast instructions as necessary...
9029 std::vector<Value*> Args;
9030 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009031 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009032 attrVec.reserve(NumCommonArgs);
9033
9034 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009035 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009036
9037 // If the return value is not being used, the type may not be compatible
9038 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009039 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009040
9041 // Add the new return attributes.
9042 if (RAttrs)
9043 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009044
9045 AI = CS.arg_begin();
9046 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9047 const Type *ParamTy = FT->getParamType(i);
9048 if ((*AI)->getType() == ParamTy) {
9049 Args.push_back(*AI);
9050 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009051 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009052 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009053 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009054 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009055 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009056
9057 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009058 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009059 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009060 }
9061
9062 // If the function takes more arguments than the call was taking, add them
9063 // now...
9064 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9065 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9066
9067 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009068 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009069 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009070 cerr << "WARNING: While resolving call to function '"
9071 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009072 } else {
9073 // Add all of the arguments in their promoted form to the arg list...
9074 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9075 const Type *PTy = getPromotedType((*AI)->getType());
9076 if (PTy != (*AI)->getType()) {
9077 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009078 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9079 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009080 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009081 InsertNewInstBefore(Cast, *Caller);
9082 Args.push_back(Cast);
9083 } else {
9084 Args.push_back(*AI);
9085 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009086
Duncan Sandse1e520f2008-01-13 08:02:44 +00009087 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009088 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009089 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9090 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009091 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009092 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009093
9094 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009095 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009096
Chris Lattner58d74912008-03-12 17:45:29 +00009097 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009098
Chris Lattner9fe38862003-06-19 17:00:31 +00009099 Instruction *NC;
9100 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009101 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009102 Args.begin(), Args.end(),
9103 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009104 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009105 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009106 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009107 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9108 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009109 CallInst *CI = cast<CallInst>(Caller);
9110 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009111 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009112 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009113 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009114 }
9115
Chris Lattner6934a042007-02-11 01:23:03 +00009116 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009117 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009118 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009119 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009120 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009121 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009122 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009123
9124 // If this is an invoke instruction, we should insert it after the first
9125 // non-phi, instruction in the normal successor block.
9126 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9127 BasicBlock::iterator I = II->getNormalDest()->begin();
9128 while (isa<PHINode>(I)) ++I;
9129 InsertNewInstBefore(NC, *I);
9130 } else {
9131 // Otherwise, it's a call, just insert cast right after the call instr
9132 InsertNewInstBefore(NC, *Caller);
9133 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009134 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009135 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009136 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009137 }
9138 }
9139
9140 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9141 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009142 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009143 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009144 return true;
9145}
9146
Duncan Sandscdb6d922007-09-17 10:26:40 +00009147// transformCallThroughTrampoline - Turn a call to a function created by the
9148// init_trampoline intrinsic into a direct call to the underlying function.
9149//
9150Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9151 Value *Callee = CS.getCalledValue();
9152 const PointerType *PTy = cast<PointerType>(Callee->getType());
9153 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009154 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009155
9156 // If the call already has the 'nest' attribute somewhere then give up -
9157 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009158 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009159 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009160
9161 IntrinsicInst *Tramp =
9162 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9163
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009164 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009165 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9166 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9167
Chris Lattner58d74912008-03-12 17:45:29 +00009168 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9169 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009170 unsigned NestIdx = 1;
9171 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009172 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009173
9174 // Look for a parameter marked with the 'nest' attribute.
9175 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9176 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009177 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009178 // Record the parameter type and any other attributes.
9179 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009180 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009181 break;
9182 }
9183
9184 if (NestTy) {
9185 Instruction *Caller = CS.getInstruction();
9186 std::vector<Value*> NewArgs;
9187 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9188
Chris Lattner58d74912008-03-12 17:45:29 +00009189 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9190 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009191
Duncan Sandscdb6d922007-09-17 10:26:40 +00009192 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009193 // mean appending it. Likewise for attributes.
9194
9195 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009196 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9197 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009198
Duncan Sandscdb6d922007-09-17 10:26:40 +00009199 {
9200 unsigned Idx = 1;
9201 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9202 do {
9203 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009204 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009205 Value *NestVal = Tramp->getOperand(3);
9206 if (NestVal->getType() != NestTy)
9207 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9208 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009209 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009210 }
9211
9212 if (I == E)
9213 break;
9214
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009215 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009216 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009217 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009218 NewAttrs.push_back
9219 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009220
9221 ++Idx, ++I;
9222 } while (1);
9223 }
9224
9225 // The trampoline may have been bitcast to a bogus type (FTy).
9226 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009227 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009228
Duncan Sandscdb6d922007-09-17 10:26:40 +00009229 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009230 NewTypes.reserve(FTy->getNumParams()+1);
9231
Duncan Sandscdb6d922007-09-17 10:26:40 +00009232 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009233 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009234 {
9235 unsigned Idx = 1;
9236 FunctionType::param_iterator I = FTy->param_begin(),
9237 E = FTy->param_end();
9238
9239 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009240 if (Idx == NestIdx)
9241 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009242 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009243
9244 if (I == E)
9245 break;
9246
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009247 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009248 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009249
9250 ++Idx, ++I;
9251 } while (1);
9252 }
9253
9254 // Replace the trampoline call with a direct call. Let the generic
9255 // code sort out any function type mismatches.
9256 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009257 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009258 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9259 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009260 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009261
9262 Instruction *NewCaller;
9263 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009264 NewCaller = InvokeInst::Create(NewCallee,
9265 II->getNormalDest(), II->getUnwindDest(),
9266 NewArgs.begin(), NewArgs.end(),
9267 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009268 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009269 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009270 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009271 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9272 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009273 if (cast<CallInst>(Caller)->isTailCall())
9274 cast<CallInst>(NewCaller)->setTailCall();
9275 cast<CallInst>(NewCaller)->
9276 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009277 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009278 }
9279 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9280 Caller->replaceAllUsesWith(NewCaller);
9281 Caller->eraseFromParent();
9282 RemoveFromWorkList(Caller);
9283 return 0;
9284 }
9285 }
9286
9287 // Replace the trampoline call with a direct call. Since there is no 'nest'
9288 // parameter, there is no need to adjust the argument list. Let the generic
9289 // code sort out any function type mismatches.
9290 Constant *NewCallee =
9291 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9292 CS.setCalledFunction(NewCallee);
9293 return CS.getInstruction();
9294}
9295
Chris Lattner7da52b22006-11-01 04:51:18 +00009296/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9297/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9298/// and a single binop.
9299Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9300 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009301 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9302 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009303 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009304 Value *LHSVal = FirstInst->getOperand(0);
9305 Value *RHSVal = FirstInst->getOperand(1);
9306
9307 const Type *LHSType = LHSVal->getType();
9308 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009309
9310 // Scan to see if all operands are the same opcode, all have one use, and all
9311 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009312 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009313 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009314 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009315 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009316 // types or GEP's with different index types.
9317 I->getOperand(0)->getType() != LHSType ||
9318 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009319 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009320
9321 // If they are CmpInst instructions, check their predicates
9322 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9323 if (cast<CmpInst>(I)->getPredicate() !=
9324 cast<CmpInst>(FirstInst)->getPredicate())
9325 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009326
9327 // Keep track of which operand needs a phi node.
9328 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9329 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009330 }
9331
Chris Lattner53738a42006-11-08 19:42:28 +00009332 // Otherwise, this is safe to transform, determine if it is profitable.
9333
9334 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9335 // Indexes are often folded into load/store instructions, so we don't want to
9336 // hide them behind a phi.
9337 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9338 return 0;
9339
Chris Lattner7da52b22006-11-01 04:51:18 +00009340 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009341 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009342 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009343 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009344 NewLHS = PHINode::Create(LHSType,
9345 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009346 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9347 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009348 InsertNewInstBefore(NewLHS, PN);
9349 LHSVal = NewLHS;
9350 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009351
9352 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009353 NewRHS = PHINode::Create(RHSType,
9354 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009355 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9356 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009357 InsertNewInstBefore(NewRHS, PN);
9358 RHSVal = NewRHS;
9359 }
9360
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009361 // Add all operands to the new PHIs.
9362 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9363 if (NewLHS) {
9364 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9365 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9366 }
9367 if (NewRHS) {
9368 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9369 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9370 }
9371 }
9372
Chris Lattner7da52b22006-11-01 04:51:18 +00009373 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009374 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009375 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009376 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009377 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009378 else {
9379 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009380 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009381 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009382}
9383
Chris Lattner76c73142006-11-01 07:13:54 +00009384/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9385/// of the block that defines it. This means that it must be obvious the value
9386/// of the load is not changed from the point of the load to the end of the
9387/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009388///
9389/// Finally, it is safe, but not profitable, to sink a load targetting a
9390/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9391/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009392static bool isSafeToSinkLoad(LoadInst *L) {
9393 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9394
9395 for (++BBI; BBI != E; ++BBI)
9396 if (BBI->mayWriteToMemory())
9397 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009398
9399 // Check for non-address taken alloca. If not address-taken already, it isn't
9400 // profitable to do this xform.
9401 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9402 bool isAddressTaken = false;
9403 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9404 UI != E; ++UI) {
9405 if (isa<LoadInst>(UI)) continue;
9406 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9407 // If storing TO the alloca, then the address isn't taken.
9408 if (SI->getOperand(1) == AI) continue;
9409 }
9410 isAddressTaken = true;
9411 break;
9412 }
9413
9414 if (!isAddressTaken)
9415 return false;
9416 }
9417
Chris Lattner76c73142006-11-01 07:13:54 +00009418 return true;
9419}
9420
Chris Lattner9fe38862003-06-19 17:00:31 +00009421
Chris Lattnerbac32862004-11-14 19:13:23 +00009422// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9423// operator and they all are only used by the PHI, PHI together their
9424// inputs, and do the operation once, to the result of the PHI.
9425Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9426 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9427
9428 // Scan the instruction, looking for input operations that can be folded away.
9429 // If all input operands to the phi are the same instruction (e.g. a cast from
9430 // the same type or "+42") we can pull the operation through the PHI, reducing
9431 // code size and simplifying code.
9432 Constant *ConstantOp = 0;
9433 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009434 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009435 if (isa<CastInst>(FirstInst)) {
9436 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009437 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009438 // Can fold binop, compare or shift here if the RHS is a constant,
9439 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009440 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009441 if (ConstantOp == 0)
9442 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009443 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9444 isVolatile = LI->isVolatile();
9445 // We can't sink the load if the loaded value could be modified between the
9446 // load and the PHI.
9447 if (LI->getParent() != PN.getIncomingBlock(0) ||
9448 !isSafeToSinkLoad(LI))
9449 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009450 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009451 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009452 return FoldPHIArgBinOpIntoPHI(PN);
9453 // Can't handle general GEPs yet.
9454 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009455 } else {
9456 return 0; // Cannot fold this operation.
9457 }
9458
9459 // Check to see if all arguments are the same operation.
9460 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9461 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9462 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009463 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009464 return 0;
9465 if (CastSrcTy) {
9466 if (I->getOperand(0)->getType() != CastSrcTy)
9467 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009468 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009469 // We can't sink the load if the loaded value could be modified between
9470 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009471 if (LI->isVolatile() != isVolatile ||
9472 LI->getParent() != PN.getIncomingBlock(i) ||
9473 !isSafeToSinkLoad(LI))
9474 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009475
9476 // If the PHI is volatile and its block has multiple successors, sinking
9477 // it would remove a load of the volatile value from the path through the
9478 // other successor.
9479 if (isVolatile &&
9480 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9481 return 0;
9482
9483
Chris Lattnerbac32862004-11-14 19:13:23 +00009484 } else if (I->getOperand(1) != ConstantOp) {
9485 return 0;
9486 }
9487 }
9488
9489 // Okay, they are all the same operation. Create a new PHI node of the
9490 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009491 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9492 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009493 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009494
9495 Value *InVal = FirstInst->getOperand(0);
9496 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009497
9498 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009499 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9500 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9501 if (NewInVal != InVal)
9502 InVal = 0;
9503 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9504 }
9505
9506 Value *PhiVal;
9507 if (InVal) {
9508 // The new PHI unions all of the same values together. This is really
9509 // common, so we handle it intelligently here for compile-time speed.
9510 PhiVal = InVal;
9511 delete NewPN;
9512 } else {
9513 InsertNewInstBefore(NewPN, PN);
9514 PhiVal = NewPN;
9515 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009516
Chris Lattnerbac32862004-11-14 19:13:23 +00009517 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009518 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009519 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009520 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009521 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009522 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009523 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009524 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009525 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9526
9527 // If this was a volatile load that we are merging, make sure to loop through
9528 // and mark all the input loads as non-volatile. If we don't do this, we will
9529 // insert a new volatile load and the old ones will not be deletable.
9530 if (isVolatile)
9531 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9532 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9533
9534 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009535}
Chris Lattnera1be5662002-05-02 17:06:02 +00009536
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009537/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9538/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009539static bool DeadPHICycle(PHINode *PN,
9540 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009541 if (PN->use_empty()) return true;
9542 if (!PN->hasOneUse()) return false;
9543
9544 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009545 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009546 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009547
9548 // Don't scan crazily complex things.
9549 if (PotentiallyDeadPHIs.size() == 16)
9550 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009551
9552 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9553 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009554
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009555 return false;
9556}
9557
Chris Lattnercf5008a2007-11-06 21:52:06 +00009558/// PHIsEqualValue - Return true if this phi node is always equal to
9559/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9560/// z = some value; x = phi (y, z); y = phi (x, z)
9561static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9562 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9563 // See if we already saw this PHI node.
9564 if (!ValueEqualPHIs.insert(PN))
9565 return true;
9566
9567 // Don't scan crazily complex things.
9568 if (ValueEqualPHIs.size() == 16)
9569 return false;
9570
9571 // Scan the operands to see if they are either phi nodes or are equal to
9572 // the value.
9573 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9574 Value *Op = PN->getIncomingValue(i);
9575 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9576 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9577 return false;
9578 } else if (Op != NonPhiInVal)
9579 return false;
9580 }
9581
9582 return true;
9583}
9584
9585
Chris Lattner473945d2002-05-06 18:06:38 +00009586// PHINode simplification
9587//
Chris Lattner7e708292002-06-25 16:13:24 +00009588Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009589 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009590 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009591
Owen Anderson7e057142006-07-10 22:03:18 +00009592 if (Value *V = PN.hasConstantValue())
9593 return ReplaceInstUsesWith(PN, V);
9594
Owen Anderson7e057142006-07-10 22:03:18 +00009595 // If all PHI operands are the same operation, pull them through the PHI,
9596 // reducing code size.
9597 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9598 PN.getIncomingValue(0)->hasOneUse())
9599 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9600 return Result;
9601
9602 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9603 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9604 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009605 if (PN.hasOneUse()) {
9606 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9607 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009608 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009609 PotentiallyDeadPHIs.insert(&PN);
9610 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9611 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9612 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009613
9614 // If this phi has a single use, and if that use just computes a value for
9615 // the next iteration of a loop, delete the phi. This occurs with unused
9616 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9617 // common case here is good because the only other things that catch this
9618 // are induction variable analysis (sometimes) and ADCE, which is only run
9619 // late.
9620 if (PHIUser->hasOneUse() &&
9621 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9622 PHIUser->use_back() == &PN) {
9623 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9624 }
9625 }
Owen Anderson7e057142006-07-10 22:03:18 +00009626
Chris Lattnercf5008a2007-11-06 21:52:06 +00009627 // We sometimes end up with phi cycles that non-obviously end up being the
9628 // same value, for example:
9629 // z = some value; x = phi (y, z); y = phi (x, z)
9630 // where the phi nodes don't necessarily need to be in the same block. Do a
9631 // quick check to see if the PHI node only contains a single non-phi value, if
9632 // so, scan to see if the phi cycle is actually equal to that value.
9633 {
9634 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9635 // Scan for the first non-phi operand.
9636 while (InValNo != NumOperandVals &&
9637 isa<PHINode>(PN.getIncomingValue(InValNo)))
9638 ++InValNo;
9639
9640 if (InValNo != NumOperandVals) {
9641 Value *NonPhiInVal = PN.getOperand(InValNo);
9642
9643 // Scan the rest of the operands to see if there are any conflicts, if so
9644 // there is no need to recursively scan other phis.
9645 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9646 Value *OpVal = PN.getIncomingValue(InValNo);
9647 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9648 break;
9649 }
9650
9651 // If we scanned over all operands, then we have one unique value plus
9652 // phi values. Scan PHI nodes to see if they all merge in each other or
9653 // the value.
9654 if (InValNo == NumOperandVals) {
9655 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9656 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9657 return ReplaceInstUsesWith(PN, NonPhiInVal);
9658 }
9659 }
9660 }
Chris Lattner60921c92003-12-19 05:58:40 +00009661 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009662}
9663
Reid Spencer17212df2006-12-12 09:18:51 +00009664static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9665 Instruction *InsertPoint,
9666 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009667 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9668 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009669 // We must cast correctly to the pointer type. Ensure that we
9670 // sign extend the integer value if it is smaller as this is
9671 // used for address computation.
9672 Instruction::CastOps opcode =
9673 (VTySize < PtrSize ? Instruction::SExt :
9674 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9675 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009676}
9677
Chris Lattnera1be5662002-05-02 17:06:02 +00009678
Chris Lattner7e708292002-06-25 16:13:24 +00009679Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009680 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009681 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009682 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009683 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009684 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009685
Chris Lattnere87597f2004-10-16 18:11:37 +00009686 if (isa<UndefValue>(GEP.getOperand(0)))
9687 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9688
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009689 bool HasZeroPointerIndex = false;
9690 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9691 HasZeroPointerIndex = C->isNullValue();
9692
9693 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009694 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009695
Chris Lattner28977af2004-04-05 01:30:19 +00009696 // Eliminate unneeded casts for indices.
9697 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009698
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009699 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009700 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009701 if (isa<SequentialType>(*GTI)) {
9702 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009703 if (CI->getOpcode() == Instruction::ZExt ||
9704 CI->getOpcode() == Instruction::SExt) {
9705 const Type *SrcTy = CI->getOperand(0)->getType();
9706 // We can eliminate a cast from i32 to i64 iff the target
9707 // is a 32-bit pointer target.
9708 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9709 MadeChange = true;
9710 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009711 }
9712 }
9713 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009714 // If we are using a wider index than needed for this platform, shrink it
9715 // to what we need. If the incoming value needs a cast instruction,
9716 // insert it. This explicit cast can make subsequent optimizations more
9717 // obvious.
9718 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009719 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009720 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009721 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009722 MadeChange = true;
9723 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009724 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9725 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009726 GEP.setOperand(i, Op);
9727 MadeChange = true;
9728 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009729 }
Chris Lattner28977af2004-04-05 01:30:19 +00009730 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009731 }
Chris Lattner28977af2004-04-05 01:30:19 +00009732 if (MadeChange) return &GEP;
9733
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009734 // If this GEP instruction doesn't move the pointer, and if the input operand
9735 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9736 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009737 if (GEP.hasAllZeroIndices()) {
9738 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9739 // If the bitcast is of an allocation, and the allocation will be
9740 // converted to match the type of the cast, don't touch this.
9741 if (isa<AllocationInst>(BCI->getOperand(0))) {
9742 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009743 if (Instruction *I = visitBitCast(*BCI)) {
9744 if (I != BCI) {
9745 I->takeName(BCI);
9746 BCI->getParent()->getInstList().insert(BCI, I);
9747 ReplaceInstUsesWith(*BCI, I);
9748 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009749 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009750 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009751 }
9752 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9753 }
9754 }
9755
Chris Lattner90ac28c2002-08-02 19:29:35 +00009756 // Combine Indices - If the source pointer to this getelementptr instruction
9757 // is a getelementptr instruction, combine the indices of the two
9758 // getelementptr instructions into a single instruction.
9759 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009760 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009761 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009762 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009763
9764 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009765 // Note that if our source is a gep chain itself that we wait for that
9766 // chain to be resolved before we perform this transformation. This
9767 // avoids us creating a TON of code in some cases.
9768 //
9769 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9770 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9771 return 0; // Wait until our source is folded to completion.
9772
Chris Lattner72588fc2007-02-15 22:48:32 +00009773 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009774
9775 // Find out whether the last index in the source GEP is a sequential idx.
9776 bool EndsWithSequential = false;
9777 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9778 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009779 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009780
Chris Lattner90ac28c2002-08-02 19:29:35 +00009781 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009782 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009783 // Replace: gep (gep %P, long B), long A, ...
9784 // With: T = long A+B; gep %P, T, ...
9785 //
Chris Lattner620ce142004-05-07 22:09:22 +00009786 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009787 if (SO1 == Constant::getNullValue(SO1->getType())) {
9788 Sum = GO1;
9789 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9790 Sum = SO1;
9791 } else {
9792 // If they aren't the same type, convert both to an integer of the
9793 // target's pointer size.
9794 if (SO1->getType() != GO1->getType()) {
9795 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009796 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009797 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009798 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009799 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009800 unsigned PS = TD->getPointerSizeInBits();
9801 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009802 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009803 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009804
Duncan Sands514ab342007-11-01 20:53:16 +00009805 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009806 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009807 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009808 } else {
9809 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009810 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9811 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009812 }
9813 }
9814 }
Chris Lattner620ce142004-05-07 22:09:22 +00009815 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9816 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9817 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009818 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +00009819 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009820 }
Chris Lattner28977af2004-04-05 01:30:19 +00009821 }
Chris Lattner620ce142004-05-07 22:09:22 +00009822
9823 // Recycle the GEP we already have if possible.
9824 if (SrcGEPOperands.size() == 2) {
9825 GEP.setOperand(0, SrcGEPOperands[0]);
9826 GEP.setOperand(1, Sum);
9827 return &GEP;
9828 } else {
9829 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9830 SrcGEPOperands.end()-1);
9831 Indices.push_back(Sum);
9832 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9833 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009834 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009835 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009836 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009837 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009838 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9839 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009840 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9841 }
9842
9843 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009844 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9845 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009846
Chris Lattner620ce142004-05-07 22:09:22 +00009847 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009848 // GEP of global variable. If all of the indices for this GEP are
9849 // constants, we can promote this to a constexpr instead of an instruction.
9850
9851 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009852 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009853 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9854 for (; I != E && isa<Constant>(*I); ++I)
9855 Indices.push_back(cast<Constant>(*I));
9856
9857 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009858 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9859 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009860
9861 // Replace all uses of the GEP with the new constexpr...
9862 return ReplaceInstUsesWith(GEP, CE);
9863 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009864 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009865 if (!isa<PointerType>(X->getType())) {
9866 // Not interesting. Source pointer must be a cast from pointer.
9867 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009868 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9869 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009870 //
9871 // This occurs when the program declares an array extern like "int X[];"
9872 //
9873 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9874 const PointerType *XTy = cast<PointerType>(X->getType());
9875 if (const ArrayType *XATy =
9876 dyn_cast<ArrayType>(XTy->getElementType()))
9877 if (const ArrayType *CATy =
9878 dyn_cast<ArrayType>(CPTy->getElementType()))
9879 if (CATy->getElementType() == XATy->getElementType()) {
9880 // At this point, we know that the cast source type is a pointer
9881 // to an array of the same type as the destination pointer
9882 // array. Because the array type is never stepped over (there
9883 // is a leading zero) we can fold the cast into this GEP.
9884 GEP.setOperand(0, X);
9885 return &GEP;
9886 }
9887 } else if (GEP.getNumOperands() == 2) {
9888 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009889 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9890 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009891 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9892 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9893 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009894 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9895 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009896 Value *Idx[2];
9897 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9898 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009899 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009900 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009901 // V and GEP are both pointer types --> BitCast
9902 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009903 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009904
9905 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009906 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009907 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009908 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009909
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009910 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009911 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009912 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009913
9914 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9915 // allow either a mul, shift, or constant here.
9916 Value *NewIdx = 0;
9917 ConstantInt *Scale = 0;
9918 if (ArrayEltSize == 1) {
9919 NewIdx = GEP.getOperand(1);
9920 Scale = ConstantInt::get(NewIdx->getType(), 1);
9921 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009922 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009923 Scale = CI;
9924 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9925 if (Inst->getOpcode() == Instruction::Shl &&
9926 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009927 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9928 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9929 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009930 NewIdx = Inst->getOperand(0);
9931 } else if (Inst->getOpcode() == Instruction::Mul &&
9932 isa<ConstantInt>(Inst->getOperand(1))) {
9933 Scale = cast<ConstantInt>(Inst->getOperand(1));
9934 NewIdx = Inst->getOperand(0);
9935 }
9936 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009937
Chris Lattner7835cdd2005-09-13 18:36:04 +00009938 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009939 // out, perform the transformation. Note, we don't know whether Scale is
9940 // signed or not. We'll use unsigned version of division/modulo
9941 // operation after making sure Scale doesn't have the sign bit set.
9942 if (Scale && Scale->getSExtValue() >= 0LL &&
9943 Scale->getZExtValue() % ArrayEltSize == 0) {
9944 Scale = ConstantInt::get(Scale->getType(),
9945 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009946 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009947 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009948 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009949 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00009950 NewIdx = InsertNewInstBefore(Sc, GEP);
9951 }
9952
9953 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009954 Value *Idx[2];
9955 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9956 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009957 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009958 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009959 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9960 // The NewGEP must be pointer typed, so must the old one -> BitCast
9961 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009962 }
9963 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009964 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009965 }
9966
Chris Lattner8a2a3112001-12-14 16:52:21 +00009967 return 0;
9968}
9969
Chris Lattner0864acf2002-11-04 16:18:53 +00009970Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9971 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009972 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009973 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9974 const Type *NewTy =
9975 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009976 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009977
9978 // Create and insert the replacement instruction...
9979 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009980 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009981 else {
9982 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009983 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009984 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009985
9986 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009987
Chris Lattner0864acf2002-11-04 16:18:53 +00009988 // Scan to the end of the allocation instructions, to skip over a block of
9989 // allocas if possible...
9990 //
9991 BasicBlock::iterator It = New;
9992 while (isa<AllocationInst>(*It)) ++It;
9993
9994 // Now that I is pointing to the first non-allocation-inst in the block,
9995 // insert our getelementptr instruction...
9996 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009997 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009998 Value *Idx[2];
9999 Idx[0] = NullIdx;
10000 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010001 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10002 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010003
10004 // Now make everything use the getelementptr instead of the original
10005 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010006 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010007 } else if (isa<UndefValue>(AI.getArraySize())) {
10008 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010009 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010010 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010011
10012 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10013 // Note that we only do this for alloca's, because malloc should allocate and
10014 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010015 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010016 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010017 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10018
Chris Lattner0864acf2002-11-04 16:18:53 +000010019 return 0;
10020}
10021
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010022Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10023 Value *Op = FI.getOperand(0);
10024
Chris Lattner17be6352004-10-18 02:59:09 +000010025 // free undef -> unreachable.
10026 if (isa<UndefValue>(Op)) {
10027 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010028 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010029 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010030 return EraseInstFromFunction(FI);
10031 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010032
Chris Lattner6160e852004-02-28 04:57:37 +000010033 // If we have 'free null' delete the instruction. This can happen in stl code
10034 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010035 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010036 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010037
10038 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10039 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10040 FI.setOperand(0, CI->getOperand(0));
10041 return &FI;
10042 }
10043
10044 // Change free (gep X, 0,0,0,0) into free(X)
10045 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10046 if (GEPI->hasAllZeroIndices()) {
10047 AddToWorkList(GEPI);
10048 FI.setOperand(0, GEPI->getOperand(0));
10049 return &FI;
10050 }
10051 }
10052
10053 // Change free(malloc) into nothing, if the malloc has a single use.
10054 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10055 if (MI->hasOneUse()) {
10056 EraseInstFromFunction(FI);
10057 return EraseInstFromFunction(*MI);
10058 }
Chris Lattner6160e852004-02-28 04:57:37 +000010059
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010060 return 0;
10061}
10062
10063
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010064/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010065static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010066 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010067 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010068 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010069
Devang Patel99db6ad2007-10-18 19:52:32 +000010070 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10071 // Instead of loading constant c string, use corresponding integer value
10072 // directly if string length is small enough.
10073 const std::string &Str = CE->getOperand(0)->getStringValue();
10074 if (!Str.empty()) {
10075 unsigned len = Str.length();
10076 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10077 unsigned numBits = Ty->getPrimitiveSizeInBits();
10078 // Replace LI with immediate integer store.
10079 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010080 APInt StrVal(numBits, 0);
10081 APInt SingleChar(numBits, 0);
10082 if (TD->isLittleEndian()) {
10083 for (signed i = len-1; i >= 0; i--) {
10084 SingleChar = (uint64_t) Str[i];
10085 StrVal = (StrVal << 8) | SingleChar;
10086 }
10087 } else {
10088 for (unsigned i = 0; i < len; i++) {
10089 SingleChar = (uint64_t) Str[i];
10090 StrVal = (StrVal << 8) | SingleChar;
10091 }
10092 // Append NULL at the end.
10093 SingleChar = 0;
10094 StrVal = (StrVal << 8) | SingleChar;
10095 }
10096 Value *NL = ConstantInt::get(StrVal);
10097 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010098 }
10099 }
10100 }
10101
Chris Lattnerb89e0712004-07-13 01:49:43 +000010102 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010103 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010104 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010105
Reid Spencer42230162007-01-22 05:51:25 +000010106 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010107 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010108 // If the source is an array, the code below will not succeed. Check to
10109 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10110 // constants.
10111 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10112 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10113 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010114 Value *Idxs[2];
10115 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10116 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010117 SrcTy = cast<PointerType>(CastOp->getType());
10118 SrcPTy = SrcTy->getElementType();
10119 }
10120
Reid Spencer42230162007-01-22 05:51:25 +000010121 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010122 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010123 // Do not allow turning this into a load of an integer, which is then
10124 // casted to a pointer, this pessimizes pointer analysis a lot.
10125 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010126 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10127 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010128
Chris Lattnerf9527852005-01-31 04:50:46 +000010129 // Okay, we are casting from one integer or pointer type to another of
10130 // the same size. Instead of casting the pointer before the load, cast
10131 // the result of the loaded value.
10132 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10133 CI->getName(),
10134 LI.isVolatile()),LI);
10135 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010136 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010137 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010138 }
10139 }
10140 return 0;
10141}
10142
Chris Lattnerc10aced2004-09-19 18:43:46 +000010143/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010144/// from this value cannot trap. If it is not obviously safe to load from the
10145/// specified pointer, we do a quick local scan of the basic block containing
10146/// ScanFrom, to determine if the address is already accessed.
10147static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010148 // If it is an alloca it is always safe to load from.
10149 if (isa<AllocaInst>(V)) return true;
10150
Duncan Sands46318cd2007-09-19 10:25:38 +000010151 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010152 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010153 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010154 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010155
10156 // Otherwise, be a little bit agressive by scanning the local block where we
10157 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010158 // from/to. If so, the previous load or store would have already trapped,
10159 // so there is no harm doing an extra load (also, CSE will later eliminate
10160 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010161 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10162
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010163 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010164 --BBI;
10165
10166 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10167 if (LI->getOperand(0) == V) return true;
10168 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10169 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010170
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010171 }
Chris Lattner8a375202004-09-19 19:18:10 +000010172 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010173}
10174
Chris Lattner8d2e8882007-08-11 18:48:48 +000010175/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10176/// until we find the underlying object a pointer is referring to or something
10177/// we don't understand. Note that the returned pointer may be offset from the
10178/// input, because we ignore GEP indices.
10179static Value *GetUnderlyingObject(Value *Ptr) {
10180 while (1) {
10181 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10182 if (CE->getOpcode() == Instruction::BitCast ||
10183 CE->getOpcode() == Instruction::GetElementPtr)
10184 Ptr = CE->getOperand(0);
10185 else
10186 return Ptr;
10187 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10188 Ptr = BCI->getOperand(0);
10189 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10190 Ptr = GEP->getOperand(0);
10191 } else {
10192 return Ptr;
10193 }
10194 }
10195}
10196
Chris Lattner833b8a42003-06-26 05:06:25 +000010197Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10198 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010199
Dan Gohman9941f742007-07-20 16:34:21 +000010200 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010201 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10202 if (KnownAlign >
10203 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10204 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010205 LI.setAlignment(KnownAlign);
10206
Chris Lattner37366c12005-05-01 04:24:53 +000010207 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010208 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010209 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010210 return Res;
10211
10212 // None of the following transforms are legal for volatile loads.
10213 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010214
Chris Lattner62f254d2005-09-12 22:00:15 +000010215 if (&LI.getParent()->front() != &LI) {
10216 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010217 // If the instruction immediately before this is a store to the same
10218 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010219 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10220 if (SI->getOperand(1) == LI.getOperand(0))
10221 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010222 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10223 if (LIB->getOperand(0) == LI.getOperand(0))
10224 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010225 }
Chris Lattner37366c12005-05-01 04:24:53 +000010226
Christopher Lambb15147e2007-12-29 07:56:53 +000010227 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10228 const Value *GEPI0 = GEPI->getOperand(0);
10229 // TODO: Consider a target hook for valid address spaces for this xform.
10230 if (isa<ConstantPointerNull>(GEPI0) &&
10231 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010232 // Insert a new store to null instruction before the load to indicate
10233 // that this code is not reachable. We do this instead of inserting
10234 // an unreachable instruction directly because we cannot modify the
10235 // CFG.
10236 new StoreInst(UndefValue::get(LI.getType()),
10237 Constant::getNullValue(Op->getType()), &LI);
10238 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10239 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010240 }
Chris Lattner37366c12005-05-01 04:24:53 +000010241
Chris Lattnere87597f2004-10-16 18:11:37 +000010242 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010243 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010244 // TODO: Consider a target hook for valid address spaces for this xform.
10245 if (isa<UndefValue>(C) || (C->isNullValue() &&
10246 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010247 // Insert a new store to null instruction before the load to indicate that
10248 // this code is not reachable. We do this instead of inserting an
10249 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010250 new StoreInst(UndefValue::get(LI.getType()),
10251 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010252 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010253 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010254
Chris Lattnere87597f2004-10-16 18:11:37 +000010255 // Instcombine load (constant global) into the value loaded.
10256 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010257 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010258 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010259
Chris Lattnere87597f2004-10-16 18:11:37 +000010260 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010261 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010262 if (CE->getOpcode() == Instruction::GetElementPtr) {
10263 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010264 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010265 if (Constant *V =
10266 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010267 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010268 if (CE->getOperand(0)->isNullValue()) {
10269 // Insert a new store to null instruction before the load to indicate
10270 // that this code is not reachable. We do this instead of inserting
10271 // an unreachable instruction directly because we cannot modify the
10272 // CFG.
10273 new StoreInst(UndefValue::get(LI.getType()),
10274 Constant::getNullValue(Op->getType()), &LI);
10275 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10276 }
10277
Reid Spencer3da59db2006-11-27 01:05:10 +000010278 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010279 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010280 return Res;
10281 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010282 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010283 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010284
10285 // If this load comes from anywhere in a constant global, and if the global
10286 // is all undef or zero, we know what it loads.
10287 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10288 if (GV->isConstant() && GV->hasInitializer()) {
10289 if (GV->getInitializer()->isNullValue())
10290 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10291 else if (isa<UndefValue>(GV->getInitializer()))
10292 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10293 }
10294 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010295
Chris Lattner37366c12005-05-01 04:24:53 +000010296 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010297 // Change select and PHI nodes to select values instead of addresses: this
10298 // helps alias analysis out a lot, allows many others simplifications, and
10299 // exposes redundancy in the code.
10300 //
10301 // Note that we cannot do the transformation unless we know that the
10302 // introduced loads cannot trap! Something like this is valid as long as
10303 // the condition is always false: load (select bool %C, int* null, int* %G),
10304 // but it would not be valid if we transformed it to load from null
10305 // unconditionally.
10306 //
10307 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10308 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010309 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10310 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010311 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010312 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010313 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010314 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010315 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010316 }
10317
Chris Lattner684fe212004-09-23 15:46:00 +000010318 // load (select (cond, null, P)) -> load P
10319 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10320 if (C->isNullValue()) {
10321 LI.setOperand(0, SI->getOperand(2));
10322 return &LI;
10323 }
10324
10325 // load (select (cond, P, null)) -> load P
10326 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10327 if (C->isNullValue()) {
10328 LI.setOperand(0, SI->getOperand(1));
10329 return &LI;
10330 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010331 }
10332 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010333 return 0;
10334}
10335
Reid Spencer55af2b52007-01-19 21:20:31 +000010336/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010337/// when possible.
10338static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10339 User *CI = cast<User>(SI.getOperand(1));
10340 Value *CastOp = CI->getOperand(0);
10341
10342 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10343 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10344 const Type *SrcPTy = SrcTy->getElementType();
10345
Reid Spencer42230162007-01-22 05:51:25 +000010346 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010347 // If the source is an array, the code below will not succeed. Check to
10348 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10349 // constants.
10350 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10351 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10352 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010353 Value* Idxs[2];
10354 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10355 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010356 SrcTy = cast<PointerType>(CastOp->getType());
10357 SrcPTy = SrcTy->getElementType();
10358 }
10359
Reid Spencer67f827c2007-01-20 23:35:48 +000010360 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10361 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10362 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010363
10364 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010365 // the same size. Instead of casting the pointer before
10366 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010367 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010368 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010369 Instruction::CastOps opcode = Instruction::BitCast;
10370 const Type* CastSrcTy = SIOp0->getType();
10371 const Type* CastDstTy = SrcPTy;
10372 if (isa<PointerType>(CastDstTy)) {
10373 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010374 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010375 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010376 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010377 opcode = Instruction::PtrToInt;
10378 }
10379 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010380 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010381 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010382 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010383 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010384 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010385 return new StoreInst(NewCast, CastOp);
10386 }
10387 }
10388 }
10389 return 0;
10390}
10391
Chris Lattner2f503e62005-01-31 05:36:43 +000010392Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10393 Value *Val = SI.getOperand(0);
10394 Value *Ptr = SI.getOperand(1);
10395
10396 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010397 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010398 ++NumCombined;
10399 return 0;
10400 }
Chris Lattner836692d2007-01-15 06:51:56 +000010401
10402 // If the RHS is an alloca with a single use, zapify the store, making the
10403 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010404 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010405 if (isa<AllocaInst>(Ptr)) {
10406 EraseInstFromFunction(SI);
10407 ++NumCombined;
10408 return 0;
10409 }
10410
10411 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10412 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10413 GEP->getOperand(0)->hasOneUse()) {
10414 EraseInstFromFunction(SI);
10415 ++NumCombined;
10416 return 0;
10417 }
10418 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010419
Dan Gohman9941f742007-07-20 16:34:21 +000010420 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010421 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10422 if (KnownAlign >
10423 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10424 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010425 SI.setAlignment(KnownAlign);
10426
Chris Lattner9ca96412006-02-08 03:25:32 +000010427 // Do really simple DSE, to catch cases where there are several consequtive
10428 // stores to the same location, separated by a few arithmetic operations. This
10429 // situation often occurs with bitfield accesses.
10430 BasicBlock::iterator BBI = &SI;
10431 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10432 --ScanInsts) {
10433 --BBI;
10434
10435 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10436 // Prev store isn't volatile, and stores to the same location?
10437 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10438 ++NumDeadStore;
10439 ++BBI;
10440 EraseInstFromFunction(*PrevSI);
10441 continue;
10442 }
10443 break;
10444 }
10445
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010446 // If this is a load, we have to stop. However, if the loaded value is from
10447 // the pointer we're loading and is producing the pointer we're storing,
10448 // then *this* store is dead (X = load P; store X -> P).
10449 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010450 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010451 EraseInstFromFunction(SI);
10452 ++NumCombined;
10453 return 0;
10454 }
10455 // Otherwise, this is a load from some other location. Stores before it
10456 // may not be dead.
10457 break;
10458 }
10459
Chris Lattner9ca96412006-02-08 03:25:32 +000010460 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010461 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010462 break;
10463 }
10464
10465
10466 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010467
10468 // store X, null -> turns into 'unreachable' in SimplifyCFG
10469 if (isa<ConstantPointerNull>(Ptr)) {
10470 if (!isa<UndefValue>(Val)) {
10471 SI.setOperand(0, UndefValue::get(Val->getType()));
10472 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010473 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010474 ++NumCombined;
10475 }
10476 return 0; // Do not modify these!
10477 }
10478
10479 // store undef, Ptr -> noop
10480 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010481 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010482 ++NumCombined;
10483 return 0;
10484 }
10485
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010486 // If the pointer destination is a cast, see if we can fold the cast into the
10487 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010488 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010489 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10490 return Res;
10491 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010492 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010493 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10494 return Res;
10495
Chris Lattner408902b2005-09-12 23:23:25 +000010496
10497 // If this store is the last instruction in the basic block, and if the block
10498 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010499 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010500 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010501 if (BI->isUnconditional())
10502 if (SimplifyStoreAtEndOfBlock(SI))
10503 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010504
Chris Lattner2f503e62005-01-31 05:36:43 +000010505 return 0;
10506}
10507
Chris Lattner3284d1f2007-04-15 00:07:55 +000010508/// SimplifyStoreAtEndOfBlock - Turn things like:
10509/// if () { *P = v1; } else { *P = v2 }
10510/// into a phi node with a store in the successor.
10511///
Chris Lattner31755a02007-04-15 01:02:18 +000010512/// Simplify things like:
10513/// *P = v1; if () { *P = v2; }
10514/// into a phi node with a store in the successor.
10515///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010516bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10517 BasicBlock *StoreBB = SI.getParent();
10518
10519 // Check to see if the successor block has exactly two incoming edges. If
10520 // so, see if the other predecessor contains a store to the same location.
10521 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010522 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010523
10524 // Determine whether Dest has exactly two predecessors and, if so, compute
10525 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010526 pred_iterator PI = pred_begin(DestBB);
10527 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010528 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010529 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010530 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010531 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010532 return false;
10533
10534 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010535 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010536 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010537 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010538 }
Chris Lattner31755a02007-04-15 01:02:18 +000010539 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010540 return false;
10541
10542
Chris Lattner31755a02007-04-15 01:02:18 +000010543 // Verify that the other block ends in a branch and is not otherwise empty.
10544 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010545 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010546 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010547 return false;
10548
Chris Lattner31755a02007-04-15 01:02:18 +000010549 // If the other block ends in an unconditional branch, check for the 'if then
10550 // else' case. there is an instruction before the branch.
10551 StoreInst *OtherStore = 0;
10552 if (OtherBr->isUnconditional()) {
10553 // If this isn't a store, or isn't a store to the same location, bail out.
10554 --BBI;
10555 OtherStore = dyn_cast<StoreInst>(BBI);
10556 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10557 return false;
10558 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010559 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010560 // destinations is StoreBB, then we have the if/then case.
10561 if (OtherBr->getSuccessor(0) != StoreBB &&
10562 OtherBr->getSuccessor(1) != StoreBB)
10563 return false;
10564
10565 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010566 // if/then triangle. See if there is a store to the same ptr as SI that
10567 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010568 for (;; --BBI) {
10569 // Check to see if we find the matching store.
10570 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10571 if (OtherStore->getOperand(1) != SI.getOperand(1))
10572 return false;
10573 break;
10574 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010575 // If we find something that may be using the stored value, or if we run
10576 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010577 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10578 BBI == OtherBB->begin())
10579 return false;
10580 }
10581
10582 // In order to eliminate the store in OtherBr, we have to
10583 // make sure nothing reads the stored value in StoreBB.
10584 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10585 // FIXME: This should really be AA driven.
10586 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10587 return false;
10588 }
10589 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010590
Chris Lattner31755a02007-04-15 01:02:18 +000010591 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010592 Value *MergedVal = OtherStore->getOperand(0);
10593 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010594 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010595 PN->reserveOperandSpace(2);
10596 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010597 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10598 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010599 }
10600
10601 // Advance to a place where it is safe to insert the new store and
10602 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010603 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010604 while (isa<PHINode>(BBI)) ++BBI;
10605 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10606 OtherStore->isVolatile()), *BBI);
10607
10608 // Nuke the old stores.
10609 EraseInstFromFunction(SI);
10610 EraseInstFromFunction(*OtherStore);
10611 ++NumCombined;
10612 return true;
10613}
10614
Chris Lattner2f503e62005-01-31 05:36:43 +000010615
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010616Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10617 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010618 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010619 BasicBlock *TrueDest;
10620 BasicBlock *FalseDest;
10621 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10622 !isa<Constant>(X)) {
10623 // Swap Destinations and condition...
10624 BI.setCondition(X);
10625 BI.setSuccessor(0, FalseDest);
10626 BI.setSuccessor(1, TrueDest);
10627 return &BI;
10628 }
10629
Reid Spencere4d87aa2006-12-23 06:05:41 +000010630 // Cannonicalize fcmp_one -> fcmp_oeq
10631 FCmpInst::Predicate FPred; Value *Y;
10632 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10633 TrueDest, FalseDest)))
10634 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10635 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10636 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010637 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010638 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10639 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010640 // Swap Destinations and condition...
10641 BI.setCondition(NewSCC);
10642 BI.setSuccessor(0, FalseDest);
10643 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010644 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010645 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010646 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010647 return &BI;
10648 }
10649
10650 // Cannonicalize icmp_ne -> icmp_eq
10651 ICmpInst::Predicate IPred;
10652 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10653 TrueDest, FalseDest)))
10654 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10655 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10656 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10657 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010658 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010659 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10660 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010661 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010662 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010663 BI.setSuccessor(0, FalseDest);
10664 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010665 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010666 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010667 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010668 return &BI;
10669 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010670
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010671 return 0;
10672}
Chris Lattner0864acf2002-11-04 16:18:53 +000010673
Chris Lattner46238a62004-07-03 00:26:11 +000010674Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10675 Value *Cond = SI.getCondition();
10676 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10677 if (I->getOpcode() == Instruction::Add)
10678 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10679 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10680 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010681 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010682 AddRHS));
10683 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010684 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010685 return &SI;
10686 }
10687 }
10688 return 0;
10689}
10690
Chris Lattner220b0cf2006-03-05 00:22:33 +000010691/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10692/// is to leave as a vector operation.
10693static bool CheapToScalarize(Value *V, bool isConstant) {
10694 if (isa<ConstantAggregateZero>(V))
10695 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010696 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010697 if (isConstant) return true;
10698 // If all elts are the same, we can extract.
10699 Constant *Op0 = C->getOperand(0);
10700 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10701 if (C->getOperand(i) != Op0)
10702 return false;
10703 return true;
10704 }
10705 Instruction *I = dyn_cast<Instruction>(V);
10706 if (!I) return false;
10707
10708 // Insert element gets simplified to the inserted element or is deleted if
10709 // this is constant idx extract element and its a constant idx insertelt.
10710 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10711 isa<ConstantInt>(I->getOperand(2)))
10712 return true;
10713 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10714 return true;
10715 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10716 if (BO->hasOneUse() &&
10717 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10718 CheapToScalarize(BO->getOperand(1), isConstant)))
10719 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010720 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10721 if (CI->hasOneUse() &&
10722 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10723 CheapToScalarize(CI->getOperand(1), isConstant)))
10724 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010725
10726 return false;
10727}
10728
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010729/// Read and decode a shufflevector mask.
10730///
10731/// It turns undef elements into values that are larger than the number of
10732/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010733static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10734 unsigned NElts = SVI->getType()->getNumElements();
10735 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10736 return std::vector<unsigned>(NElts, 0);
10737 if (isa<UndefValue>(SVI->getOperand(2)))
10738 return std::vector<unsigned>(NElts, 2*NElts);
10739
10740 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010741 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010742 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10743 if (isa<UndefValue>(CP->getOperand(i)))
10744 Result.push_back(NElts*2); // undef -> 8
10745 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010746 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010747 return Result;
10748}
10749
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010750/// FindScalarElement - Given a vector and an element number, see if the scalar
10751/// value is already around as a register, for example if it were inserted then
10752/// extracted from the vector.
10753static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010754 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10755 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010756 unsigned Width = PTy->getNumElements();
10757 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010758 return UndefValue::get(PTy->getElementType());
10759
10760 if (isa<UndefValue>(V))
10761 return UndefValue::get(PTy->getElementType());
10762 else if (isa<ConstantAggregateZero>(V))
10763 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010764 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010765 return CP->getOperand(EltNo);
10766 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10767 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010768 if (!isa<ConstantInt>(III->getOperand(2)))
10769 return 0;
10770 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010771
10772 // If this is an insert to the element we are looking for, return the
10773 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010774 if (EltNo == IIElt)
10775 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010776
10777 // Otherwise, the insertelement doesn't modify the value, recurse on its
10778 // vector input.
10779 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010780 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010781 unsigned InEl = getShuffleMask(SVI)[EltNo];
10782 if (InEl < Width)
10783 return FindScalarElement(SVI->getOperand(0), InEl);
10784 else if (InEl < Width*2)
10785 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10786 else
10787 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010788 }
10789
10790 // Otherwise, we don't know.
10791 return 0;
10792}
10793
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010794Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010795
Dan Gohman07a96762007-07-16 14:29:03 +000010796 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010797 if (isa<UndefValue>(EI.getOperand(0)))
10798 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10799
Dan Gohman07a96762007-07-16 14:29:03 +000010800 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010801 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10802 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10803
Reid Spencer9d6565a2007-02-15 02:26:10 +000010804 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010805 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010806 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010807 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010808 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010809 if (C->getOperand(i) != op0) {
10810 op0 = 0;
10811 break;
10812 }
10813 if (op0)
10814 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010815 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010816
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010817 // If extracting a specified index from the vector, see if we can recursively
10818 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010819 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010820 unsigned IndexVal = IdxC->getZExtValue();
10821 unsigned VectorWidth =
10822 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10823
10824 // If this is extracting an invalid index, turn this into undef, to avoid
10825 // crashing the code below.
10826 if (IndexVal >= VectorWidth)
10827 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10828
Chris Lattner867b99f2006-10-05 06:55:50 +000010829 // This instruction only demands the single element from the input vector.
10830 // If the input vector has a single use, simplify it based on this use
10831 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010832 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010833 uint64_t UndefElts;
10834 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010835 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010836 UndefElts)) {
10837 EI.setOperand(0, V);
10838 return &EI;
10839 }
10840 }
10841
Reid Spencerb83eb642006-10-20 07:07:24 +000010842 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010843 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010844
10845 // If the this extractelement is directly using a bitcast from a vector of
10846 // the same number of elements, see if we can find the source element from
10847 // it. In this case, we will end up needing to bitcast the scalars.
10848 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10849 if (const VectorType *VT =
10850 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10851 if (VT->getNumElements() == VectorWidth)
10852 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10853 return new BitCastInst(Elt, EI.getType());
10854 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010855 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010856
Chris Lattner73fa49d2006-05-25 22:53:38 +000010857 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010858 if (I->hasOneUse()) {
10859 // Push extractelement into predecessor operation if legal and
10860 // profitable to do so
10861 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010862 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10863 if (CheapToScalarize(BO, isConstantElt)) {
10864 ExtractElementInst *newEI0 =
10865 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10866 EI.getName()+".lhs");
10867 ExtractElementInst *newEI1 =
10868 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10869 EI.getName()+".rhs");
10870 InsertNewInstBefore(newEI0, EI);
10871 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010872 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000010873 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010874 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010875 unsigned AS =
10876 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010877 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10878 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010879 GetElementPtrInst *GEP =
10880 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010881 InsertNewInstBefore(GEP, EI);
10882 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010883 }
10884 }
10885 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10886 // Extracting the inserted element?
10887 if (IE->getOperand(2) == EI.getOperand(1))
10888 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10889 // If the inserted and extracted elements are constants, they must not
10890 // be the same value, extract from the pre-inserted value instead.
10891 if (isa<Constant>(IE->getOperand(2)) &&
10892 isa<Constant>(EI.getOperand(1))) {
10893 AddUsesToWorkList(EI);
10894 EI.setOperand(0, IE->getOperand(0));
10895 return &EI;
10896 }
10897 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10898 // If this is extracting an element from a shufflevector, figure out where
10899 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010900 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10901 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010902 Value *Src;
10903 if (SrcIdx < SVI->getType()->getNumElements())
10904 Src = SVI->getOperand(0);
10905 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10906 SrcIdx -= SVI->getType()->getNumElements();
10907 Src = SVI->getOperand(1);
10908 } else {
10909 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010910 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010911 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010912 }
10913 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010914 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010915 return 0;
10916}
10917
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010918/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10919/// elements from either LHS or RHS, return the shuffle mask and true.
10920/// Otherwise, return false.
10921static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10922 std::vector<Constant*> &Mask) {
10923 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10924 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010925 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010926
10927 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010928 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010929 return true;
10930 } else if (V == LHS) {
10931 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010932 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010933 return true;
10934 } else if (V == RHS) {
10935 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010936 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010937 return true;
10938 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10939 // If this is an insert of an extract from some other vector, include it.
10940 Value *VecOp = IEI->getOperand(0);
10941 Value *ScalarOp = IEI->getOperand(1);
10942 Value *IdxOp = IEI->getOperand(2);
10943
Chris Lattnerd929f062006-04-27 21:14:21 +000010944 if (!isa<ConstantInt>(IdxOp))
10945 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010946 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010947
10948 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10949 // Okay, we can handle this if the vector we are insertinting into is
10950 // transitively ok.
10951 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10952 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010953 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010954 return true;
10955 }
10956 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10957 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010958 EI->getOperand(0)->getType() == V->getType()) {
10959 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010960 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010961
10962 // This must be extracting from either LHS or RHS.
10963 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10964 // Okay, we can handle this if the vector we are insertinting into is
10965 // transitively ok.
10966 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10967 // If so, update the mask to reflect the inserted value.
10968 if (EI->getOperand(0) == LHS) {
10969 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010970 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010971 } else {
10972 assert(EI->getOperand(0) == RHS);
10973 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010974 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010975
10976 }
10977 return true;
10978 }
10979 }
10980 }
10981 }
10982 }
10983 // TODO: Handle shufflevector here!
10984
10985 return false;
10986}
10987
10988/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10989/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10990/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010991static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010992 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010993 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010994 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010995 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010996 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010997
10998 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010999 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011000 return V;
11001 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011002 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011003 return V;
11004 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11005 // If this is an insert of an extract from some other vector, include it.
11006 Value *VecOp = IEI->getOperand(0);
11007 Value *ScalarOp = IEI->getOperand(1);
11008 Value *IdxOp = IEI->getOperand(2);
11009
11010 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11011 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11012 EI->getOperand(0)->getType() == V->getType()) {
11013 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011014 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11015 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011016
11017 // Either the extracted from or inserted into vector must be RHSVec,
11018 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011019 if (EI->getOperand(0) == RHS || RHS == 0) {
11020 RHS = EI->getOperand(0);
11021 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011022 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011023 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011024 return V;
11025 }
11026
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011027 if (VecOp == RHS) {
11028 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011029 // Everything but the extracted element is replaced with the RHS.
11030 for (unsigned i = 0; i != NumElts; ++i) {
11031 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011032 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011033 }
11034 return V;
11035 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011036
11037 // If this insertelement is a chain that comes from exactly these two
11038 // vectors, return the vector and the effective shuffle.
11039 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11040 return EI->getOperand(0);
11041
Chris Lattnerefb47352006-04-15 01:39:45 +000011042 }
11043 }
11044 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011045 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011046
11047 // Otherwise, can't do anything fancy. Return an identity vector.
11048 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011049 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011050 return V;
11051}
11052
11053Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11054 Value *VecOp = IE.getOperand(0);
11055 Value *ScalarOp = IE.getOperand(1);
11056 Value *IdxOp = IE.getOperand(2);
11057
Chris Lattner599ded12007-04-09 01:11:16 +000011058 // Inserting an undef or into an undefined place, remove this.
11059 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11060 ReplaceInstUsesWith(IE, VecOp);
11061
Chris Lattnerefb47352006-04-15 01:39:45 +000011062 // If the inserted element was extracted from some other vector, and if the
11063 // indexes are constant, try to turn this into a shufflevector operation.
11064 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11065 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11066 EI->getOperand(0)->getType() == IE.getType()) {
11067 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011068 unsigned ExtractedIdx =
11069 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011070 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011071
11072 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11073 return ReplaceInstUsesWith(IE, VecOp);
11074
11075 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11076 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11077
11078 // If we are extracting a value from a vector, then inserting it right
11079 // back into the same place, just use the input vector.
11080 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11081 return ReplaceInstUsesWith(IE, VecOp);
11082
11083 // We could theoretically do this for ANY input. However, doing so could
11084 // turn chains of insertelement instructions into a chain of shufflevector
11085 // instructions, and right now we do not merge shufflevectors. As such,
11086 // only do this in a situation where it is clear that there is benefit.
11087 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11088 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11089 // the values of VecOp, except then one read from EIOp0.
11090 // Build a new shuffle mask.
11091 std::vector<Constant*> Mask;
11092 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011093 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011094 else {
11095 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011096 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011097 NumVectorElts));
11098 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011099 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011100 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011101 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011102 }
11103
11104 // If this insertelement isn't used by some other insertelement, turn it
11105 // (and any insertelements it points to), into one big shuffle.
11106 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11107 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011108 Value *RHS = 0;
11109 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11110 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11111 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011112 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011113 }
11114 }
11115 }
11116
11117 return 0;
11118}
11119
11120
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011121Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11122 Value *LHS = SVI.getOperand(0);
11123 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011124 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011125
11126 bool MadeChange = false;
11127
Chris Lattner867b99f2006-10-05 06:55:50 +000011128 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011129 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011130 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11131
Chris Lattnere4929dd2007-01-05 07:36:08 +000011132 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011133 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011134 if (isa<UndefValue>(SVI.getOperand(1))) {
11135 // Scan to see if there are any references to the RHS. If so, replace them
11136 // with undef element refs and set MadeChange to true.
11137 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11138 if (Mask[i] >= e && Mask[i] != 2*e) {
11139 Mask[i] = 2*e;
11140 MadeChange = true;
11141 }
11142 }
11143
11144 if (MadeChange) {
11145 // Remap any references to RHS to use LHS.
11146 std::vector<Constant*> Elts;
11147 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11148 if (Mask[i] == 2*e)
11149 Elts.push_back(UndefValue::get(Type::Int32Ty));
11150 else
11151 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11152 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011153 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011154 }
11155 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011156
Chris Lattner863bcff2006-05-25 23:48:38 +000011157 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11158 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11159 if (LHS == RHS || isa<UndefValue>(LHS)) {
11160 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011161 // shuffle(undef,undef,mask) -> undef.
11162 return ReplaceInstUsesWith(SVI, LHS);
11163 }
11164
Chris Lattner863bcff2006-05-25 23:48:38 +000011165 // Remap any references to RHS to use LHS.
11166 std::vector<Constant*> Elts;
11167 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011168 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011169 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011170 else {
11171 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11172 (Mask[i] < e && isa<UndefValue>(LHS)))
11173 Mask[i] = 2*e; // Turn into undef.
11174 else
11175 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011176 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011177 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011178 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011179 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011180 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011181 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011182 LHS = SVI.getOperand(0);
11183 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011184 MadeChange = true;
11185 }
11186
Chris Lattner7b2e27922006-05-26 00:29:06 +000011187 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011188 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011189
Chris Lattner863bcff2006-05-25 23:48:38 +000011190 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11191 if (Mask[i] >= e*2) continue; // Ignore undef values.
11192 // Is this an identity shuffle of the LHS value?
11193 isLHSID &= (Mask[i] == i);
11194
11195 // Is this an identity shuffle of the RHS value?
11196 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011197 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011198
Chris Lattner863bcff2006-05-25 23:48:38 +000011199 // Eliminate identity shuffles.
11200 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11201 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011202
Chris Lattner7b2e27922006-05-26 00:29:06 +000011203 // If the LHS is a shufflevector itself, see if we can combine it with this
11204 // one without producing an unusual shuffle. Here we are really conservative:
11205 // we are absolutely afraid of producing a shuffle mask not in the input
11206 // program, because the code gen may not be smart enough to turn a merged
11207 // shuffle into two specific shuffles: it may produce worse code. As such,
11208 // we only merge two shuffles if the result is one of the two input shuffle
11209 // masks. In this case, merging the shuffles just removes one instruction,
11210 // which we know is safe. This is good for things like turning:
11211 // (splat(splat)) -> splat.
11212 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11213 if (isa<UndefValue>(RHS)) {
11214 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11215
11216 std::vector<unsigned> NewMask;
11217 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11218 if (Mask[i] >= 2*e)
11219 NewMask.push_back(2*e);
11220 else
11221 NewMask.push_back(LHSMask[Mask[i]]);
11222
11223 // If the result mask is equal to the src shuffle or this shuffle mask, do
11224 // the replacement.
11225 if (NewMask == LHSMask || NewMask == Mask) {
11226 std::vector<Constant*> Elts;
11227 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11228 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011229 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011230 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011231 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011232 }
11233 }
11234 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11235 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011236 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011237 }
11238 }
11239 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011240
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011241 return MadeChange ? &SVI : 0;
11242}
11243
11244
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011245
Chris Lattnerea1c4542004-12-08 23:43:58 +000011246
11247/// TryToSinkInstruction - Try to move the specified instruction from its
11248/// current block into the beginning of DestBlock, which can only happen if it's
11249/// safe to move the instruction past all of the instructions between it and the
11250/// end of its block.
11251static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11252 assert(I->hasOneUse() && "Invariants didn't hold!");
11253
Chris Lattner108e9022005-10-27 17:13:11 +000011254 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011255 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11256 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011257
Chris Lattnerea1c4542004-12-08 23:43:58 +000011258 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011259 if (isa<AllocaInst>(I) && I->getParent() ==
11260 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011261 return false;
11262
Chris Lattner96a52a62004-12-09 07:14:34 +000011263 // We can only sink load instructions if there is nothing between the load and
11264 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011265 if (I->mayReadFromMemory()) {
11266 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011267 Scan != E; ++Scan)
11268 if (Scan->mayWriteToMemory())
11269 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011270 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011271
11272 BasicBlock::iterator InsertPos = DestBlock->begin();
11273 while (isa<PHINode>(InsertPos)) ++InsertPos;
11274
Chris Lattner4bc5f802005-08-08 19:11:57 +000011275 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011276 ++NumSunkInst;
11277 return true;
11278}
11279
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011280
11281/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11282/// all reachable code to the worklist.
11283///
11284/// This has a couple of tricks to make the code faster and more powerful. In
11285/// particular, we constant fold and DCE instructions as we go, to avoid adding
11286/// them to the worklist (this significantly speeds up instcombine on code where
11287/// many instructions are dead or constant). Additionally, if we find a branch
11288/// whose condition is a known constant, we only visit the reachable successors.
11289///
11290static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011291 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011292 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011293 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011294 std::vector<BasicBlock*> Worklist;
11295 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011296
Chris Lattner2c7718a2007-03-23 19:17:18 +000011297 while (!Worklist.empty()) {
11298 BB = Worklist.back();
11299 Worklist.pop_back();
11300
11301 // We have now visited this block! If we've already been here, ignore it.
11302 if (!Visited.insert(BB)) continue;
11303
11304 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11305 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011306
Chris Lattner2c7718a2007-03-23 19:17:18 +000011307 // DCE instruction if trivially dead.
11308 if (isInstructionTriviallyDead(Inst)) {
11309 ++NumDeadInst;
11310 DOUT << "IC: DCE: " << *Inst;
11311 Inst->eraseFromParent();
11312 continue;
11313 }
11314
11315 // ConstantProp instruction if trivially constant.
11316 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11317 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11318 Inst->replaceAllUsesWith(C);
11319 ++NumConstProp;
11320 Inst->eraseFromParent();
11321 continue;
11322 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011323
Chris Lattner2c7718a2007-03-23 19:17:18 +000011324 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011325 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011326
11327 // Recursively visit successors. If this is a branch or switch on a
11328 // constant, only visit the reachable successor.
11329 TerminatorInst *TI = BB->getTerminator();
11330 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11331 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11332 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011333 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011334 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011335 continue;
11336 }
11337 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11338 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11339 // See if this is an explicit destination.
11340 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11341 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011342 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011343 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011344 continue;
11345 }
11346
11347 // Otherwise it is the default destination.
11348 Worklist.push_back(SI->getSuccessor(0));
11349 continue;
11350 }
11351 }
11352
11353 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11354 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011355 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011356}
11357
Chris Lattnerec9c3582007-03-03 02:04:50 +000011358bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011359 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011360 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011361
11362 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11363 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011364
Chris Lattnerb3d59702005-07-07 20:40:38 +000011365 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011366 // Do a depth-first traversal of the function, populate the worklist with
11367 // the reachable instructions. Ignore blocks that are not reachable. Keep
11368 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011369 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011370 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011371
Chris Lattnerb3d59702005-07-07 20:40:38 +000011372 // Do a quick scan over the function. If we find any blocks that are
11373 // unreachable, remove any instructions inside of them. This prevents
11374 // the instcombine code from having to deal with some bad special cases.
11375 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11376 if (!Visited.count(BB)) {
11377 Instruction *Term = BB->getTerminator();
11378 while (Term != BB->begin()) { // Remove instrs bottom-up
11379 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011380
Bill Wendlingb7427032006-11-26 09:46:52 +000011381 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011382 ++NumDeadInst;
11383
11384 if (!I->use_empty())
11385 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11386 I->eraseFromParent();
11387 }
11388 }
11389 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011390
Chris Lattnerdbab3862007-03-02 21:28:56 +000011391 while (!Worklist.empty()) {
11392 Instruction *I = RemoveOneFromWorkList();
11393 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011394
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011395 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011396 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011397 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011398 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011399 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011400 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011401
Bill Wendlingb7427032006-11-26 09:46:52 +000011402 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011403
11404 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011405 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011406 continue;
11407 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011408
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011409 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011410 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011411 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011412
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011413 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011414 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011415 ReplaceInstUsesWith(*I, C);
11416
Chris Lattner62b14df2002-09-02 04:59:56 +000011417 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011418 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011419 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011420 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011421 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011422
Chris Lattnerea1c4542004-12-08 23:43:58 +000011423 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011424 // FIXME: Remove GetResultInst test when first class support for aggregates
11425 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011426 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011427 BasicBlock *BB = I->getParent();
11428 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11429 if (UserParent != BB) {
11430 bool UserIsSuccessor = false;
11431 // See if the user is one of our successors.
11432 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11433 if (*SI == UserParent) {
11434 UserIsSuccessor = true;
11435 break;
11436 }
11437
11438 // If the user is one of our immediate successors, and if that successor
11439 // only has us as a predecessors (we'd have to split the critical edge
11440 // otherwise), we can keep going.
11441 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11442 next(pred_begin(UserParent)) == pred_end(UserParent))
11443 // Okay, the CFG is simple enough, try to sink this instruction.
11444 Changed |= TryToSinkInstruction(I, UserParent);
11445 }
11446 }
11447
Chris Lattner8a2a3112001-12-14 16:52:21 +000011448 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011449#ifndef NDEBUG
11450 std::string OrigI;
11451#endif
11452 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011453 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011454 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011455 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011456 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011457 DOUT << "IC: Old = " << *I
11458 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011459
Chris Lattnerf523d062004-06-09 05:08:07 +000011460 // Everything uses the new instruction now.
11461 I->replaceAllUsesWith(Result);
11462
11463 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011464 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011465 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011466
Chris Lattner6934a042007-02-11 01:23:03 +000011467 // Move the name to the new instruction first.
11468 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011469
11470 // Insert the new instruction into the basic block...
11471 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011472 BasicBlock::iterator InsertPos = I;
11473
11474 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11475 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11476 ++InsertPos;
11477
11478 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011479
Chris Lattner00d51312004-05-01 23:27:23 +000011480 // Make sure that we reprocess all operands now that we reduced their
11481 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011482 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011483
Chris Lattnerf523d062004-06-09 05:08:07 +000011484 // Instructions can end up on the worklist more than once. Make sure
11485 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011486 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011487
11488 // Erase the old instruction.
11489 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011490 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011491#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011492 DOUT << "IC: Mod = " << OrigI
11493 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011494#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011495
Chris Lattner90ac28c2002-08-02 19:29:35 +000011496 // If the instruction was modified, it's possible that it is now dead.
11497 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011498 if (isInstructionTriviallyDead(I)) {
11499 // Make sure we process all operands now that we are reducing their
11500 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011501 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011502
Chris Lattner00d51312004-05-01 23:27:23 +000011503 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011504 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011505 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011506 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011507 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011508 AddToWorkList(I);
11509 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011510 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011511 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011512 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011513 }
11514 }
11515
Chris Lattnerec9c3582007-03-03 02:04:50 +000011516 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011517
11518 // Do an explicit clear, this shrinks the map if needed.
11519 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011520 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011521}
11522
Chris Lattnerec9c3582007-03-03 02:04:50 +000011523
11524bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011525 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11526
Chris Lattnerec9c3582007-03-03 02:04:50 +000011527 bool EverMadeChange = false;
11528
11529 // Iterate while there is work to do.
11530 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011531 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011532 EverMadeChange = true;
11533 return EverMadeChange;
11534}
11535
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011536FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011537 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011538}
Brian Gaeked0fde302003-11-11 22:41:34 +000011539