blob: f3591879f7bb039c14f2bbe9bd7682d14ed884f6 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000048#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000051#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000052#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000054#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
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
Reid Spencer17212df2006-12-12 09:18:51 +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 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000387
Devang Patel19974732007-05-03 01:11:54 +0000388 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000389 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000390}
391
Chris Lattner4f98c562003-03-10 21:43:22 +0000392// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000393// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000394static unsigned getComplexity(Value *V) {
395 if (isa<Instruction>(V)) {
396 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000397 return 3;
398 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000399 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000400 if (isa<Argument>(V)) return 3;
401 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000402}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000403
Chris Lattnerc8802d22003-03-11 00:12:48 +0000404// isOnlyUse - Return true if this instruction will be deleted if we stop using
405// it.
406static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000407 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000408}
409
Chris Lattner4cb170c2004-02-23 06:38:22 +0000410// getPromotedType - Return the specified type promoted as it would be to pass
411// though a va_arg area...
412static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000413 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
414 if (ITy->getBitWidth() < 32)
415 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000416 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000417 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000418}
419
Reid Spencer3da59db2006-11-27 01:05:10 +0000420/// getBitCastOperand - If the specified operand is a CastInst or a constant
421/// expression bitcast, return the operand value, otherwise return null.
422static Value *getBitCastOperand(Value *V) {
423 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000424 return I->getOperand(0);
425 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000426 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000427 return CE->getOperand(0);
428 return 0;
429}
430
Reid Spencer3da59db2006-11-27 01:05:10 +0000431/// This function is a wrapper around CastInst::isEliminableCastPair. It
432/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000433static Instruction::CastOps
434isEliminableCastPair(
435 const CastInst *CI, ///< The first cast instruction
436 unsigned opcode, ///< The opcode of the second cast instruction
437 const Type *DstTy, ///< The target type for the second cast instruction
438 TargetData *TD ///< The target data for pointer size
439) {
440
441 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
442 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000443
Reid Spencer3da59db2006-11-27 01:05:10 +0000444 // Get the opcodes of the two Cast instructions
445 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
446 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000447
Reid Spencer3da59db2006-11-27 01:05:10 +0000448 return Instruction::CastOps(
449 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
450 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000451}
452
453/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
454/// in any code being generated. It does not require codegen if V is simple
455/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000456static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
457 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000458 if (V->getType() == Ty || isa<Constant>(V)) return false;
459
Chris Lattner01575b72006-05-25 23:24:33 +0000460 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000461 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000462 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000463 return false;
464 return true;
465}
466
467/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
468/// InsertBefore instruction. This is specialized a bit to avoid inserting
469/// casts that are known to not do anything...
470///
Reid Spencer17212df2006-12-12 09:18:51 +0000471Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
472 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000473 Instruction *InsertBefore) {
474 if (V->getType() == DestTy) return V;
475 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000476 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000477
Reid Spencer17212df2006-12-12 09:18:51 +0000478 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000479}
480
Chris Lattner4f98c562003-03-10 21:43:22 +0000481// SimplifyCommutative - This performs a few simplifications for commutative
482// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000483//
Chris Lattner4f98c562003-03-10 21:43:22 +0000484// 1. Order operands such that they are listed from right (least complex) to
485// left (most complex). This puts constants before unary operators before
486// binary operators.
487//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000488// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
489// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000490//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000491bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000492 bool Changed = false;
493 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
494 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000495
Chris Lattner4f98c562003-03-10 21:43:22 +0000496 if (!I.isAssociative()) return Changed;
497 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000498 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
499 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
500 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000501 Constant *Folded = ConstantExpr::get(I.getOpcode(),
502 cast<Constant>(I.getOperand(1)),
503 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000504 I.setOperand(0, Op->getOperand(0));
505 I.setOperand(1, Folded);
506 return true;
507 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
508 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
509 isOnlyUse(Op) && isOnlyUse(Op1)) {
510 Constant *C1 = cast<Constant>(Op->getOperand(1));
511 Constant *C2 = cast<Constant>(Op1->getOperand(1));
512
513 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000514 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000515 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
516 Op1->getOperand(0),
517 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000518 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000519 I.setOperand(0, New);
520 I.setOperand(1, Folded);
521 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000522 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000523 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000524 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000525}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000526
Reid Spencere4d87aa2006-12-23 06:05:41 +0000527/// SimplifyCompare - For a CmpInst this function just orders the operands
528/// so that theyare listed from right (least complex) to left (most complex).
529/// This puts constants before unary operators before binary operators.
530bool InstCombiner::SimplifyCompare(CmpInst &I) {
531 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
532 return false;
533 I.swapOperands();
534 // Compare instructions are not associative so there's nothing else we can do.
535 return true;
536}
537
Chris Lattner8d969642003-03-10 23:06:50 +0000538// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
539// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000540//
Chris Lattner8d969642003-03-10 23:06:50 +0000541static inline Value *dyn_castNegVal(Value *V) {
542 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000543 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000544
Chris Lattner0ce85802004-12-14 20:08:06 +0000545 // Constants can be considered to be negated values if they can be folded.
546 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
547 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000548 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000549}
550
Chris Lattner8d969642003-03-10 23:06:50 +0000551static inline Value *dyn_castNotVal(Value *V) {
552 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000553 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000554
555 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000556 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000557 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000558 return 0;
559}
560
Chris Lattnerc8802d22003-03-11 00:12:48 +0000561// dyn_castFoldableMul - If this value is a multiply that can be folded into
562// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000563// non-constant operand of the multiply, and set CST to point to the multiplier.
564// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000565//
Chris Lattner50af16a2004-11-13 19:50:12 +0000566static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000567 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000568 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000569 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000570 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000571 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000572 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000573 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000574 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000575 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000576 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000577 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000578 return I->getOperand(0);
579 }
580 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000581 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000582}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000583
Chris Lattner574da9b2005-01-13 20:14:25 +0000584/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
585/// expression, return it.
586static User *dyn_castGetElementPtr(Value *V) {
587 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
588 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
589 if (CE->getOpcode() == Instruction::GetElementPtr)
590 return cast<User>(V);
591 return false;
592}
593
Dan Gohmaneee962e2008-04-10 18:43:06 +0000594/// getOpcode - If this is an Instruction or a ConstantExpr, return the
595/// opcode value. Otherwise return UserOp1.
596static unsigned getOpcode(User *U) {
597 if (Instruction *I = dyn_cast<Instruction>(U))
598 return I->getOpcode();
599 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
600 return CE->getOpcode();
601 // Use UserOp1 to mean there's no opcode.
602 return Instruction::UserOp1;
603}
604
Reid Spencer7177c3a2007-03-25 05:33:51 +0000605/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000606static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000607 APInt Val(C->getValue());
608 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000609}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000610/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000611static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000612 APInt Val(C->getValue());
613 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000614}
615/// Add - Add two ConstantInts together
616static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
617 return ConstantInt::get(C1->getValue() + C2->getValue());
618}
619/// And - Bitwise AND two ConstantInts together
620static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
621 return ConstantInt::get(C1->getValue() & C2->getValue());
622}
623/// Subtract - Subtract one ConstantInt from another
624static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
625 return ConstantInt::get(C1->getValue() - C2->getValue());
626}
627/// Multiply - Multiply two ConstantInts together
628static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
629 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000630}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000631/// MultiplyOverflows - True if the multiply can not be expressed in an int
632/// this size.
633static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
634 uint32_t W = C1->getBitWidth();
635 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
636 if (sign) {
637 LHSExt.sext(W * 2);
638 RHSExt.sext(W * 2);
639 } else {
640 LHSExt.zext(W * 2);
641 RHSExt.zext(W * 2);
642 }
643
644 APInt MulExt = LHSExt * RHSExt;
645
646 if (sign) {
647 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
648 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
649 return MulExt.slt(Min) || MulExt.sgt(Max);
650 } else
651 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
652}
Chris Lattner955f3312004-09-28 21:48:02 +0000653
Chris Lattner68d5ff22006-02-09 07:38:58 +0000654/// ComputeMaskedBits - Determine which of the bits specified in Mask are
655/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000656/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
657/// processing.
658/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
659/// we cannot optimize based on the assumption that it is zero without changing
660/// it to be an explicit zero. If we don't change it to zero, other code could
661/// optimized based on the contradictory assumption that it is non-zero.
662/// Because instcombine aggressively folds operations with undef args anyway,
663/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000664void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
665 APInt& KnownZero, APInt& KnownOne,
666 unsigned Depth) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000667 assert(V && "No Value?");
668 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000669 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000670 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
671 "Not integer or pointer type!");
672 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
673 (!isa<IntegerType>(V->getType()) ||
674 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000675 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000676 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000677 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000678 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
679 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000680 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000681 KnownZero = ~KnownOne & Mask;
682 return;
683 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000684 // Null is all-zeros.
685 if (isa<ConstantPointerNull>(V)) {
686 KnownOne.clear();
687 KnownZero = Mask;
688 return;
689 }
690 // The address of an aligned GlobalValue has trailing zeros.
691 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
692 unsigned Align = GV->getAlignment();
693 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
694 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
695 if (Align > 0)
696 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
697 CountTrailingZeros_32(Align));
698 else
699 KnownZero.clear();
700 KnownOne.clear();
701 return;
702 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000703
Dan Gohman23e8b712008-04-28 17:02:21 +0000704 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
705
Reid Spencer3e7594f2007-03-08 01:46:38 +0000706 if (Depth == 6 || Mask == 0)
707 return; // Limit search depth.
708
Dan Gohmaneee962e2008-04-10 18:43:06 +0000709 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000710 if (!I) return;
711
712 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000713 switch (getOpcode(I)) {
714 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000715 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000716 // If either the LHS or the RHS are Zero, the result is zero.
717 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000718 APInt Mask2(Mask & ~KnownZero);
719 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000720 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
721 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
722
723 // Output known-1 bits are only known if set in both the LHS & RHS.
724 KnownOne &= KnownOne2;
725 // Output known-0 are known to be clear if zero in either the LHS | RHS.
726 KnownZero |= KnownZero2;
727 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000728 }
729 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000730 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000731 APInt Mask2(Mask & ~KnownOne);
732 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000733 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
734 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
735
736 // Output known-0 bits are only known if clear in both the LHS & RHS.
737 KnownZero &= KnownZero2;
738 // Output known-1 are known to be set if set in either the LHS | RHS.
739 KnownOne |= KnownOne2;
740 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000741 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000742 case Instruction::Xor: {
743 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
744 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
745 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
746 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
747
748 // Output known-0 bits are known if clear or set in both the LHS & RHS.
749 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
750 // Output known-1 are known to be set if set in only one of the LHS, RHS.
751 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
752 KnownZero = KnownZeroOut;
753 return;
754 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000755 case Instruction::Mul: {
756 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
757 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
758 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
759 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
760 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
761
762 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman23e8b712008-04-28 17:02:21 +0000763 // Also compute a conserative estimate for high known-0 bits.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000764 // More trickiness is possible, but this is sufficient for the
765 // interesting case of alignment computation.
766 KnownOne.clear();
767 unsigned TrailZ = KnownZero.countTrailingOnes() +
768 KnownZero2.countTrailingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +0000769 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman42ac9292008-05-07 00:35:55 +0000770 KnownZero2.countLeadingOnes(),
771 BitWidth) - BitWidth;
Dan Gohman23e8b712008-04-28 17:02:21 +0000772
Dan Gohmaneee962e2008-04-10 18:43:06 +0000773 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000774 LeadZ = std::min(LeadZ, BitWidth);
775 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
776 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000777 KnownZero &= Mask;
778 return;
779 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000780 case Instruction::UDiv: {
781 // For the purposes of computing leading zeros we can conservatively
782 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1d9cd502008-05-02 21:30:02 +0000783 // be less than the denominator.
Dan Gohman23e8b712008-04-28 17:02:21 +0000784 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
785 ComputeMaskedBits(I->getOperand(0),
786 AllOnes, KnownZero2, KnownOne2, Depth+1);
787 unsigned LeadZ = KnownZero2.countLeadingOnes();
788
789 KnownOne2.clear();
790 KnownZero2.clear();
791 ComputeMaskedBits(I->getOperand(1),
792 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1d9cd502008-05-02 21:30:02 +0000793 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
794 if (RHSUnknownLeadingOnes != BitWidth)
795 LeadZ = std::min(BitWidth,
796 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000797
798 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
799 return;
800 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000801 case Instruction::Select:
802 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
803 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
804 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
805 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
806
807 // Only known if known in both the LHS and RHS.
808 KnownOne &= KnownOne2;
809 KnownZero &= KnownZero2;
810 return;
811 case Instruction::FPTrunc:
812 case Instruction::FPExt:
813 case Instruction::FPToUI:
814 case Instruction::FPToSI:
815 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000816 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000817 return; // Can't work with floating point.
818 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000819 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000820 // We can't handle these if we don't know the pointer size.
821 if (!TD) return;
822 // Fall through and handle them the same as zext/trunc.
823 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000824 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000825 // All these have integer operands
Dan Gohmaneee962e2008-04-10 18:43:06 +0000826 const Type *SrcTy = I->getOperand(0)->getType();
827 uint32_t SrcBitWidth = TD ?
828 TD->getTypeSizeInBits(SrcTy) :
829 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000830 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000831 MaskIn.zextOrTrunc(SrcBitWidth);
832 KnownZero.zextOrTrunc(SrcBitWidth);
833 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000834 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000835 KnownZero.zextOrTrunc(BitWidth);
836 KnownOne.zextOrTrunc(BitWidth);
837 // Any top bits are known to be zero.
838 if (BitWidth > SrcBitWidth)
839 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000840 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000841 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000842 case Instruction::BitCast: {
843 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000844 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000845 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
846 return;
847 }
848 break;
849 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000850 case Instruction::SExt: {
851 // Compute the bits in the result that are not present in the input.
852 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000853 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000854
Zhou Shengaa305ab2007-03-28 02:19:03 +0000855 APInt MaskIn(Mask);
856 MaskIn.trunc(SrcBitWidth);
857 KnownZero.trunc(SrcBitWidth);
858 KnownOne.trunc(SrcBitWidth);
859 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000860 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000861 KnownZero.zext(BitWidth);
862 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000863
864 // If the sign bit of the input is known set or clear, then we know the
865 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000866 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000867 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000868 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000869 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000870 return;
871 }
872 case Instruction::Shl:
873 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
874 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000875 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000876 APInt Mask2(Mask.lshr(ShiftAmt));
877 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000878 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000879 KnownZero <<= ShiftAmt;
880 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000881 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000882 return;
883 }
884 break;
885 case Instruction::LShr:
886 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
887 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
888 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000889 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000890
891 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000892 APInt Mask2(Mask.shl(ShiftAmt));
893 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000894 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
895 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
896 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000897 // high bits known zero.
898 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000899 return;
900 }
901 break;
902 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000903 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000904 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
905 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000906 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000907
908 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000909 APInt Mask2(Mask.shl(ShiftAmt));
910 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000911 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
912 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
913 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
914
Zhou Shengaa305ab2007-03-28 02:19:03 +0000915 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
916 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000917 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000918 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000919 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000920 return;
921 }
922 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000923 case Instruction::Sub: {
924 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
925 // We know that the top bits of C-X are clear if X contains less bits
926 // than C (i.e. no wrap-around can happen). For example, 20-X is
927 // positive if we can prove that X is >= 0 and < 16.
928 if (!CLHS->getValue().isNegative()) {
929 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
930 // NLZ can't be BitWidth with no sign bit
931 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000932 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
933 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000934
Dan Gohman23e8b712008-04-28 17:02:21 +0000935 // If all of the MaskV bits are known to be zero, then we know the
936 // output top bits are zero, because we now know that the output is
937 // from [0-C].
938 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000939 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
940 // Top bits known zero.
941 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000942 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000943 }
944 }
945 }
946 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000947 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000948 // Output known-0 bits are known if clear or set in both the low clear bits
949 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
950 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000951 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
952 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
953 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
954 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
955
956 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
957 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
958 KnownZeroOut = std::min(KnownZeroOut,
959 KnownZero2.countTrailingOnes());
960
961 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000962 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000963 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000964 case Instruction::SRem:
965 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
966 APInt RA = Rem->getValue();
967 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000968 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000969 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
970 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
971
972 // The sign of a remainder is equal to the sign of the first
973 // operand (zero being positive).
974 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
975 KnownZero2 |= ~LowBits;
976 else if (KnownOne2[BitWidth-1])
977 KnownOne2 |= ~LowBits;
978
979 KnownZero |= KnownZero2 & Mask;
980 KnownOne |= KnownOne2 & Mask;
981
982 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
983 }
984 }
985 break;
Dan Gohman23e8b712008-04-28 17:02:21 +0000986 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000987 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
988 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +0000989 if (RA.isPowerOf2()) {
990 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000991 APInt Mask2 = LowBits & Mask;
992 KnownZero |= ~LowBits & Mask;
993 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
994 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +0000995 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000996 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000997 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000998
999 // Since the result is less than or equal to either operand, any leading
1000 // zero bits in either operand must also exist in the result.
1001 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1002 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1003 Depth+1);
1004 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1005 Depth+1);
1006
1007 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1008 KnownZero2.countLeadingOnes());
1009 KnownOne.clear();
1010 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001011 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001012 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001013
1014 case Instruction::Alloca:
1015 case Instruction::Malloc: {
1016 AllocationInst *AI = cast<AllocationInst>(V);
1017 unsigned Align = AI->getAlignment();
1018 if (Align == 0 && TD) {
1019 if (isa<AllocaInst>(AI))
1020 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1021 else if (isa<MallocInst>(AI)) {
1022 // Malloc returns maximally aligned memory.
1023 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1024 Align =
1025 std::max(Align,
1026 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1027 Align =
1028 std::max(Align,
1029 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1030 }
1031 }
1032
1033 if (Align > 0)
1034 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1035 CountTrailingZeros_32(Align));
1036 break;
1037 }
1038 case Instruction::GetElementPtr: {
1039 // Analyze all of the subscripts of this getelementptr instruction
1040 // to determine if we can prove known low zero bits.
1041 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1042 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1043 ComputeMaskedBits(I->getOperand(0), LocalMask,
1044 LocalKnownZero, LocalKnownOne, Depth+1);
1045 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1046
1047 gep_type_iterator GTI = gep_type_begin(I);
1048 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1049 Value *Index = I->getOperand(i);
1050 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1051 // Handle struct member offset arithmetic.
1052 if (!TD) return;
1053 const StructLayout *SL = TD->getStructLayout(STy);
1054 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1055 uint64_t Offset = SL->getElementOffset(Idx);
1056 TrailZ = std::min(TrailZ,
1057 CountTrailingZeros_64(Offset));
1058 } else {
1059 // Handle array index arithmetic.
1060 const Type *IndexedTy = GTI.getIndexedType();
1061 if (!IndexedTy->isSized()) return;
1062 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1063 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1064 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1065 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1066 ComputeMaskedBits(Index, LocalMask,
1067 LocalKnownZero, LocalKnownOne, Depth+1);
1068 TrailZ = std::min(TrailZ,
1069 CountTrailingZeros_64(TypeSize) +
1070 LocalKnownZero.countTrailingOnes());
1071 }
1072 }
1073
1074 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1075 break;
1076 }
1077 case Instruction::PHI: {
1078 PHINode *P = cast<PHINode>(I);
1079 // Handle the case of a simple two-predecessor recurrence PHI.
1080 // There's a lot more that could theoretically be done here, but
1081 // this is sufficient to catch some interesting cases.
1082 if (P->getNumIncomingValues() == 2) {
1083 for (unsigned i = 0; i != 2; ++i) {
1084 Value *L = P->getIncomingValue(i);
1085 Value *R = P->getIncomingValue(!i);
1086 User *LU = dyn_cast<User>(L);
1087 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1088 // Check for operations that have the property that if
1089 // both their operands have low zero bits, the result
1090 // will have low zero bits.
1091 if (Opcode == Instruction::Add ||
1092 Opcode == Instruction::Sub ||
1093 Opcode == Instruction::And ||
1094 Opcode == Instruction::Or ||
1095 Opcode == Instruction::Mul) {
1096 Value *LL = LU->getOperand(0);
1097 Value *LR = LU->getOperand(1);
1098 // Find a recurrence.
1099 if (LL == I)
1100 L = LR;
1101 else if (LR == I)
1102 L = LL;
1103 else
1104 break;
1105 // Ok, we have a PHI of the form L op= R. Check for low
1106 // zero bits.
1107 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1108 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1109 Mask2 = APInt::getLowBitsSet(BitWidth,
1110 KnownZero2.countTrailingOnes());
1111 KnownOne2.clear();
1112 KnownZero2.clear();
1113 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1114 KnownZero = Mask &
1115 APInt::getLowBitsSet(BitWidth,
1116 KnownZero2.countTrailingOnes());
1117 break;
1118 }
1119 }
1120 }
1121 break;
1122 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001123 case Instruction::Call:
1124 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1125 switch (II->getIntrinsicID()) {
1126 default: break;
1127 case Intrinsic::ctpop:
1128 case Intrinsic::ctlz:
1129 case Intrinsic::cttz: {
1130 unsigned LowBits = Log2_32(BitWidth)+1;
1131 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1132 break;
1133 }
1134 }
1135 }
1136 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001137 }
1138}
1139
Reid Spencere7816b52007-03-08 01:52:58 +00001140/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1141/// this predicate to simplify operations downstream. Mask is known to be zero
1142/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001143bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1144 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001145 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001146 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1147 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1148 return (KnownZero & Mask) == Mask;
1149}
1150
Chris Lattner255d8912006-02-11 09:31:47 +00001151/// ShrinkDemandedConstant - Check to see if the specified operand of the
1152/// specified instruction is a constant integer. If so, check to see if there
1153/// are any bits set in the constant that are not demanded. If so, shrink the
1154/// constant and return true.
1155static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001156 APInt Demanded) {
1157 assert(I && "No instruction?");
1158 assert(OpNo < I->getNumOperands() && "Operand index too large");
1159
1160 // If the operand is not a constant integer, nothing to do.
1161 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1162 if (!OpC) return false;
1163
1164 // If there are no bits set that aren't demanded, nothing to do.
1165 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1166 if ((~Demanded & OpC->getValue()) == 0)
1167 return false;
1168
1169 // This instruction is producing bits that are not demanded. Shrink the RHS.
1170 Demanded &= OpC->getValue();
1171 I->setOperand(OpNo, ConstantInt::get(Demanded));
1172 return true;
1173}
1174
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001175// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1176// set of known zero and one bits, compute the maximum and minimum values that
1177// could have the specified known zero and known one bits, returning them in
1178// min/max.
1179static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001180 const APInt& KnownZero,
1181 const APInt& KnownOne,
1182 APInt& Min, APInt& Max) {
1183 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1184 assert(KnownZero.getBitWidth() == BitWidth &&
1185 KnownOne.getBitWidth() == BitWidth &&
1186 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1187 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001188 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001189
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001190 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1191 // bit if it is unknown.
1192 Min = KnownOne;
1193 Max = KnownOne|UnknownBits;
1194
Zhou Sheng4acf1552007-03-28 05:15:57 +00001195 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001196 Min.set(BitWidth-1);
1197 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001198 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001199}
1200
1201// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1202// a set of known zero and one bits, compute the maximum and minimum values that
1203// could have the specified known zero and known one bits, returning them in
1204// min/max.
1205static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001206 const APInt &KnownZero,
1207 const APInt &KnownOne,
1208 APInt &Min, APInt &Max) {
1209 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001210 assert(KnownZero.getBitWidth() == BitWidth &&
1211 KnownOne.getBitWidth() == BitWidth &&
1212 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1213 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001214 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001215
1216 // The minimum value is when the unknown bits are all zeros.
1217 Min = KnownOne;
1218 // The maximum value is when the unknown bits are all ones.
1219 Max = KnownOne|UnknownBits;
1220}
Chris Lattner255d8912006-02-11 09:31:47 +00001221
Reid Spencer8cb68342007-03-12 17:25:59 +00001222/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1223/// value based on the demanded bits. When this function is called, it is known
1224/// that only the bits set in DemandedMask of the result of V are ever used
1225/// downstream. Consequently, depending on the mask and V, it may be possible
1226/// to replace V with a constant or one of its operands. In such cases, this
1227/// function does the replacement and returns true. In all other cases, it
1228/// returns false after analyzing the expression and setting KnownOne and known
1229/// to be one in the expression. KnownZero contains all the bits that are known
1230/// to be zero in the expression. These are provided to potentially allow the
1231/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1232/// the expression. KnownOne and KnownZero always follow the invariant that
1233/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1234/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1235/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1236/// and KnownOne must all be the same.
1237bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1238 APInt& KnownZero, APInt& KnownOne,
1239 unsigned Depth) {
1240 assert(V != 0 && "Null pointer of Value???");
1241 assert(Depth <= 6 && "Limit Search Depth");
1242 uint32_t BitWidth = DemandedMask.getBitWidth();
1243 const IntegerType *VTy = cast<IntegerType>(V->getType());
1244 assert(VTy->getBitWidth() == BitWidth &&
1245 KnownZero.getBitWidth() == BitWidth &&
1246 KnownOne.getBitWidth() == BitWidth &&
1247 "Value *V, DemandedMask, KnownZero and KnownOne \
1248 must have same BitWidth");
1249 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1250 // We know all of the bits for a constant!
1251 KnownOne = CI->getValue() & DemandedMask;
1252 KnownZero = ~KnownOne & DemandedMask;
1253 return false;
1254 }
1255
Zhou Sheng96704452007-03-14 03:21:24 +00001256 KnownZero.clear();
1257 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001258 if (!V->hasOneUse()) { // Other users may use these bits.
1259 if (Depth != 0) { // Not at the root.
1260 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1261 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1262 return false;
1263 }
1264 // If this is the root being simplified, allow it to have multiple uses,
1265 // just set the DemandedMask to all bits.
1266 DemandedMask = APInt::getAllOnesValue(BitWidth);
1267 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1268 if (V != UndefValue::get(VTy))
1269 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1270 return false;
1271 } else if (Depth == 6) { // Limit search depth.
1272 return false;
1273 }
1274
1275 Instruction *I = dyn_cast<Instruction>(V);
1276 if (!I) return false; // Only analyze instructions.
1277
Reid Spencer8cb68342007-03-12 17:25:59 +00001278 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1279 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1280 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001281 default:
1282 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1283 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001284 case Instruction::And:
1285 // If either the LHS or the RHS are Zero, the result is zero.
1286 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1287 RHSKnownZero, RHSKnownOne, Depth+1))
1288 return true;
1289 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1290 "Bits known to be one AND zero?");
1291
1292 // If something is known zero on the RHS, the bits aren't demanded on the
1293 // LHS.
1294 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1295 LHSKnownZero, LHSKnownOne, Depth+1))
1296 return true;
1297 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1298 "Bits known to be one AND zero?");
1299
1300 // If all of the demanded bits are known 1 on one side, return the other.
1301 // These bits cannot contribute to the result of the 'and'.
1302 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1303 (DemandedMask & ~LHSKnownZero))
1304 return UpdateValueUsesWith(I, I->getOperand(0));
1305 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1306 (DemandedMask & ~RHSKnownZero))
1307 return UpdateValueUsesWith(I, I->getOperand(1));
1308
1309 // If all of the demanded bits in the inputs are known zeros, return zero.
1310 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1311 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1312
1313 // If the RHS is a constant, see if we can simplify it.
1314 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1315 return UpdateValueUsesWith(I, I);
1316
1317 // Output known-1 bits are only known if set in both the LHS & RHS.
1318 RHSKnownOne &= LHSKnownOne;
1319 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1320 RHSKnownZero |= LHSKnownZero;
1321 break;
1322 case Instruction::Or:
1323 // If either the LHS or the RHS are One, the result is One.
1324 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1325 RHSKnownZero, RHSKnownOne, Depth+1))
1326 return true;
1327 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1328 "Bits known to be one AND zero?");
1329 // If something is known one on the RHS, the bits aren't demanded on the
1330 // LHS.
1331 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1332 LHSKnownZero, LHSKnownOne, Depth+1))
1333 return true;
1334 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1335 "Bits known to be one AND zero?");
1336
1337 // If all of the demanded bits are known zero on one side, return the other.
1338 // These bits cannot contribute to the result of the 'or'.
1339 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1340 (DemandedMask & ~LHSKnownOne))
1341 return UpdateValueUsesWith(I, I->getOperand(0));
1342 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1343 (DemandedMask & ~RHSKnownOne))
1344 return UpdateValueUsesWith(I, I->getOperand(1));
1345
1346 // If all of the potentially set bits on one side are known to be set on
1347 // the other side, just use the 'other' side.
1348 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1349 (DemandedMask & (~RHSKnownZero)))
1350 return UpdateValueUsesWith(I, I->getOperand(0));
1351 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1352 (DemandedMask & (~LHSKnownZero)))
1353 return UpdateValueUsesWith(I, I->getOperand(1));
1354
1355 // If the RHS is a constant, see if we can simplify it.
1356 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1357 return UpdateValueUsesWith(I, I);
1358
1359 // Output known-0 bits are only known if clear in both the LHS & RHS.
1360 RHSKnownZero &= LHSKnownZero;
1361 // Output known-1 are known to be set if set in either the LHS | RHS.
1362 RHSKnownOne |= LHSKnownOne;
1363 break;
1364 case Instruction::Xor: {
1365 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1366 RHSKnownZero, RHSKnownOne, Depth+1))
1367 return true;
1368 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1369 "Bits known to be one AND zero?");
1370 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1371 LHSKnownZero, LHSKnownOne, Depth+1))
1372 return true;
1373 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1374 "Bits known to be one AND zero?");
1375
1376 // If all of the demanded bits are known zero on one side, return the other.
1377 // These bits cannot contribute to the result of the 'xor'.
1378 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1379 return UpdateValueUsesWith(I, I->getOperand(0));
1380 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1381 return UpdateValueUsesWith(I, I->getOperand(1));
1382
1383 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1384 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1385 (RHSKnownOne & LHSKnownOne);
1386 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1387 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1388 (RHSKnownOne & LHSKnownZero);
1389
1390 // If all of the demanded bits are known to be zero on one side or the
1391 // other, turn this into an *inclusive* or.
1392 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1393 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1394 Instruction *Or =
1395 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1396 I->getName());
1397 InsertNewInstBefore(Or, *I);
1398 return UpdateValueUsesWith(I, Or);
1399 }
1400
1401 // If all of the demanded bits on one side are known, and all of the set
1402 // bits on that side are also known to be set on the other side, turn this
1403 // into an AND, as we know the bits will be cleared.
1404 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1405 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1406 // all known
1407 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1408 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1409 Instruction *And =
1410 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1411 InsertNewInstBefore(And, *I);
1412 return UpdateValueUsesWith(I, And);
1413 }
1414 }
1415
1416 // If the RHS is a constant, see if we can simplify it.
1417 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1418 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1419 return UpdateValueUsesWith(I, I);
1420
1421 RHSKnownZero = KnownZeroOut;
1422 RHSKnownOne = KnownOneOut;
1423 break;
1424 }
1425 case Instruction::Select:
1426 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1427 RHSKnownZero, RHSKnownOne, Depth+1))
1428 return true;
1429 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1430 LHSKnownZero, LHSKnownOne, Depth+1))
1431 return true;
1432 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1433 "Bits known to be one AND zero?");
1434 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1435 "Bits known to be one AND zero?");
1436
1437 // If the operands are constants, see if we can simplify them.
1438 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1439 return UpdateValueUsesWith(I, I);
1440 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1441 return UpdateValueUsesWith(I, I);
1442
1443 // Only known if known in both the LHS and RHS.
1444 RHSKnownOne &= LHSKnownOne;
1445 RHSKnownZero &= LHSKnownZero;
1446 break;
1447 case Instruction::Trunc: {
1448 uint32_t truncBf =
1449 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001450 DemandedMask.zext(truncBf);
1451 RHSKnownZero.zext(truncBf);
1452 RHSKnownOne.zext(truncBf);
1453 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1454 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001455 return true;
1456 DemandedMask.trunc(BitWidth);
1457 RHSKnownZero.trunc(BitWidth);
1458 RHSKnownOne.trunc(BitWidth);
1459 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1460 "Bits known to be one AND zero?");
1461 break;
1462 }
1463 case Instruction::BitCast:
1464 if (!I->getOperand(0)->getType()->isInteger())
1465 return false;
1466
1467 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1468 RHSKnownZero, RHSKnownOne, Depth+1))
1469 return true;
1470 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1471 "Bits known to be one AND zero?");
1472 break;
1473 case Instruction::ZExt: {
1474 // Compute the bits in the result that are not present in the input.
1475 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001476 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001477
Zhou Shengd48653a2007-03-29 04:45:55 +00001478 DemandedMask.trunc(SrcBitWidth);
1479 RHSKnownZero.trunc(SrcBitWidth);
1480 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001481 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1482 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001483 return true;
1484 DemandedMask.zext(BitWidth);
1485 RHSKnownZero.zext(BitWidth);
1486 RHSKnownOne.zext(BitWidth);
1487 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1488 "Bits known to be one AND zero?");
1489 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001490 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001491 break;
1492 }
1493 case Instruction::SExt: {
1494 // Compute the bits in the result that are not present in the input.
1495 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001496 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001497
Reid Spencer8cb68342007-03-12 17:25:59 +00001498 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001499 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001500
Zhou Sheng01542f32007-03-29 02:26:30 +00001501 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001502 // If any of the sign extended bits are demanded, we know that the sign
1503 // bit is demanded.
1504 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001505 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001506
Zhou Shengd48653a2007-03-29 04:45:55 +00001507 InputDemandedBits.trunc(SrcBitWidth);
1508 RHSKnownZero.trunc(SrcBitWidth);
1509 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001510 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1511 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001512 return true;
1513 InputDemandedBits.zext(BitWidth);
1514 RHSKnownZero.zext(BitWidth);
1515 RHSKnownOne.zext(BitWidth);
1516 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1517 "Bits known to be one AND zero?");
1518
1519 // If the sign bit of the input is known set or clear, then we know the
1520 // top bits of the result.
1521
1522 // If the input sign bit is known zero, or if the NewBits are not demanded
1523 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001524 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001525 {
1526 // Convert to ZExt cast
1527 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1528 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001529 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001530 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001531 }
1532 break;
1533 }
1534 case Instruction::Add: {
1535 // Figure out what the input bits are. If the top bits of the and result
1536 // are not demanded, then the add doesn't demand them from its input
1537 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001538 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001539
1540 // If there is a constant on the RHS, there are a variety of xformations
1541 // we can do.
1542 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1543 // If null, this should be simplified elsewhere. Some of the xforms here
1544 // won't work if the RHS is zero.
1545 if (RHS->isZero())
1546 break;
1547
1548 // If the top bit of the output is demanded, demand everything from the
1549 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001550 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001551
1552 // Find information about known zero/one bits in the input.
1553 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1554 LHSKnownZero, LHSKnownOne, Depth+1))
1555 return true;
1556
1557 // If the RHS of the add has bits set that can't affect the input, reduce
1558 // the constant.
1559 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1560 return UpdateValueUsesWith(I, I);
1561
1562 // Avoid excess work.
1563 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1564 break;
1565
1566 // Turn it into OR if input bits are zero.
1567 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1568 Instruction *Or =
1569 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1570 I->getName());
1571 InsertNewInstBefore(Or, *I);
1572 return UpdateValueUsesWith(I, Or);
1573 }
1574
1575 // We can say something about the output known-zero and known-one bits,
1576 // depending on potential carries from the input constant and the
1577 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1578 // bits set and the RHS constant is 0x01001, then we know we have a known
1579 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1580
1581 // To compute this, we first compute the potential carry bits. These are
1582 // the bits which may be modified. I'm not aware of a better way to do
1583 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001584 const APInt& RHSVal = RHS->getValue();
1585 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001586
1587 // Now that we know which bits have carries, compute the known-1/0 sets.
1588
1589 // Bits are known one if they are known zero in one operand and one in the
1590 // other, and there is no input carry.
1591 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1592 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1593
1594 // Bits are known zero if they are known zero in both operands and there
1595 // is no input carry.
1596 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1597 } else {
1598 // If the high-bits of this ADD are not demanded, then it does not demand
1599 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001600 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001601 // Right fill the mask of bits for this ADD to demand the most
1602 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001603 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001604 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1605 LHSKnownZero, LHSKnownOne, Depth+1))
1606 return true;
1607 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1608 LHSKnownZero, LHSKnownOne, Depth+1))
1609 return true;
1610 }
1611 }
1612 break;
1613 }
1614 case Instruction::Sub:
1615 // If the high-bits of this SUB are not demanded, then it does not demand
1616 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001617 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001618 // Right fill the mask of bits for this SUB to demand the most
1619 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001620 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001621 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001622 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1623 LHSKnownZero, LHSKnownOne, Depth+1))
1624 return true;
1625 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1626 LHSKnownZero, LHSKnownOne, Depth+1))
1627 return true;
1628 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001629 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1630 // the known zeros and ones.
1631 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001632 break;
1633 case Instruction::Shl:
1634 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001635 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001636 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1637 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001638 RHSKnownZero, RHSKnownOne, Depth+1))
1639 return true;
1640 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1641 "Bits known to be one AND zero?");
1642 RHSKnownZero <<= ShiftAmt;
1643 RHSKnownOne <<= ShiftAmt;
1644 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001645 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001646 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001647 }
1648 break;
1649 case Instruction::LShr:
1650 // For a logical shift right
1651 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001652 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001653
Reid Spencer8cb68342007-03-12 17:25:59 +00001654 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001655 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1656 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001657 RHSKnownZero, RHSKnownOne, Depth+1))
1658 return true;
1659 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1660 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001661 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1662 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001663 if (ShiftAmt) {
1664 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001665 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001666 RHSKnownZero |= HighBits; // high bits known zero.
1667 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001668 }
1669 break;
1670 case Instruction::AShr:
1671 // If this is an arithmetic shift right and only the low-bit is set, we can
1672 // always convert this into a logical shr, even if the shift amount is
1673 // variable. The low bit of the shift cannot be an input sign bit unless
1674 // the shift amount is >= the size of the datatype, which is undefined.
1675 if (DemandedMask == 1) {
1676 // Perform the logical shift right.
1677 Value *NewVal = BinaryOperator::createLShr(
1678 I->getOperand(0), I->getOperand(1), I->getName());
1679 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1680 return UpdateValueUsesWith(I, NewVal);
1681 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001682
1683 // If the sign bit is the only bit demanded by this ashr, then there is no
1684 // need to do it, the shift doesn't change the high bit.
1685 if (DemandedMask.isSignBit())
1686 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001687
1688 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001689 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001690
Reid Spencer8cb68342007-03-12 17:25:59 +00001691 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001692 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001693 // If any of the "high bits" are demanded, we should set the sign bit as
1694 // demanded.
1695 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1696 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001697 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001698 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001699 RHSKnownZero, RHSKnownOne, Depth+1))
1700 return true;
1701 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1702 "Bits known to be one AND zero?");
1703 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001704 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001705 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1706 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1707
1708 // Handle the sign bits.
1709 APInt SignBit(APInt::getSignBit(BitWidth));
1710 // Adjust to where it is now in the mask.
1711 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1712
1713 // If the input sign bit is known to be zero, or if none of the top bits
1714 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001715 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001716 (HighBits & ~DemandedMask) == HighBits) {
1717 // Perform the logical shift right.
1718 Value *NewVal = BinaryOperator::createLShr(
1719 I->getOperand(0), SA, I->getName());
1720 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1721 return UpdateValueUsesWith(I, NewVal);
1722 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1723 RHSKnownOne |= HighBits;
1724 }
1725 }
1726 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001727 case Instruction::SRem:
1728 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1729 APInt RA = Rem->getValue();
1730 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001731 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001732 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1733 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1734 LHSKnownZero, LHSKnownOne, Depth+1))
1735 return true;
1736
1737 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1738 LHSKnownZero |= ~LowBits;
1739 else if (LHSKnownOne[BitWidth-1])
1740 LHSKnownOne |= ~LowBits;
1741
1742 KnownZero |= LHSKnownZero & DemandedMask;
1743 KnownOne |= LHSKnownOne & DemandedMask;
1744
1745 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1746 }
1747 }
1748 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001749 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001750 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1751 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001752 if (RA.isPowerOf2()) {
1753 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001754 APInt Mask2 = LowBits & DemandedMask;
1755 KnownZero |= ~LowBits & DemandedMask;
1756 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1757 KnownZero, KnownOne, Depth+1))
1758 return true;
1759
1760 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001761 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001762 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001763 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001764
1765 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1766 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001767 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1768 KnownZero2, KnownOne2, Depth+1))
1769 return true;
1770
Dan Gohman23e8b712008-04-28 17:02:21 +00001771 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001772 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001773 KnownZero2, KnownOne2, Depth+1))
1774 return true;
1775
1776 Leaders = std::max(Leaders,
1777 KnownZero2.countLeadingOnes());
1778 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001779 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001780 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001781 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001782
1783 // If the client is only demanding bits that we know, return the known
1784 // constant.
1785 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1786 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1787 return false;
1788}
1789
Chris Lattner867b99f2006-10-05 06:55:50 +00001790
1791/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1792/// 64 or fewer elements. DemandedElts contains the set of elements that are
1793/// actually used by the caller. This method analyzes which elements of the
1794/// operand are undef and returns that information in UndefElts.
1795///
1796/// If the information about demanded elements can be used to simplify the
1797/// operation, the operation is simplified, then the resultant value is
1798/// returned. This returns null if no change was made.
1799Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1800 uint64_t &UndefElts,
1801 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001802 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001803 assert(VWidth <= 64 && "Vector too wide to analyze!");
1804 uint64_t EltMask = ~0ULL >> (64-VWidth);
1805 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1806 "Invalid DemandedElts!");
1807
1808 if (isa<UndefValue>(V)) {
1809 // If the entire vector is undefined, just return this info.
1810 UndefElts = EltMask;
1811 return 0;
1812 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1813 UndefElts = EltMask;
1814 return UndefValue::get(V->getType());
1815 }
1816
1817 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001818 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1819 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001820 Constant *Undef = UndefValue::get(EltTy);
1821
1822 std::vector<Constant*> Elts;
1823 for (unsigned i = 0; i != VWidth; ++i)
1824 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1825 Elts.push_back(Undef);
1826 UndefElts |= (1ULL << i);
1827 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1828 Elts.push_back(Undef);
1829 UndefElts |= (1ULL << i);
1830 } else { // Otherwise, defined.
1831 Elts.push_back(CP->getOperand(i));
1832 }
1833
1834 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001835 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001836 return NewCP != CP ? NewCP : 0;
1837 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001838 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001839 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001840 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001841 Constant *Zero = Constant::getNullValue(EltTy);
1842 Constant *Undef = UndefValue::get(EltTy);
1843 std::vector<Constant*> Elts;
1844 for (unsigned i = 0; i != VWidth; ++i)
1845 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1846 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001847 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001848 }
1849
1850 if (!V->hasOneUse()) { // Other users may use these bits.
1851 if (Depth != 0) { // Not at the root.
1852 // TODO: Just compute the UndefElts information recursively.
1853 return false;
1854 }
1855 return false;
1856 } else if (Depth == 10) { // Limit search depth.
1857 return false;
1858 }
1859
1860 Instruction *I = dyn_cast<Instruction>(V);
1861 if (!I) return false; // Only analyze instructions.
1862
1863 bool MadeChange = false;
1864 uint64_t UndefElts2;
1865 Value *TmpV;
1866 switch (I->getOpcode()) {
1867 default: break;
1868
1869 case Instruction::InsertElement: {
1870 // If this is a variable index, we don't know which element it overwrites.
1871 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001872 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001873 if (Idx == 0) {
1874 // Note that we can't propagate undef elt info, because we don't know
1875 // which elt is getting updated.
1876 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1877 UndefElts2, Depth+1);
1878 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1879 break;
1880 }
1881
1882 // If this is inserting an element that isn't demanded, remove this
1883 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001884 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001885 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1886 return AddSoonDeadInstToWorklist(*I, 0);
1887
1888 // Otherwise, the element inserted overwrites whatever was there, so the
1889 // input demanded set is simpler than the output set.
1890 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1891 DemandedElts & ~(1ULL << IdxNo),
1892 UndefElts, Depth+1);
1893 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1894
1895 // The inserted element is defined.
1896 UndefElts |= 1ULL << IdxNo;
1897 break;
1898 }
Chris Lattner69878332007-04-14 22:29:23 +00001899 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001900 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001901 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1902 if (!VTy) break;
1903 unsigned InVWidth = VTy->getNumElements();
1904 uint64_t InputDemandedElts = 0;
1905 unsigned Ratio;
1906
1907 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001908 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001909 // elements as are demanded of us.
1910 Ratio = 1;
1911 InputDemandedElts = DemandedElts;
1912 } else if (VWidth > InVWidth) {
1913 // Untested so far.
1914 break;
1915
1916 // If there are more elements in the result than there are in the source,
1917 // then an input element is live if any of the corresponding output
1918 // elements are live.
1919 Ratio = VWidth/InVWidth;
1920 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1921 if (DemandedElts & (1ULL << OutIdx))
1922 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1923 }
1924 } else {
1925 // Untested so far.
1926 break;
1927
1928 // If there are more elements in the source than there are in the result,
1929 // then an input element is live if the corresponding output element is
1930 // live.
1931 Ratio = InVWidth/VWidth;
1932 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1933 if (DemandedElts & (1ULL << InIdx/Ratio))
1934 InputDemandedElts |= 1ULL << InIdx;
1935 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001936
Chris Lattner69878332007-04-14 22:29:23 +00001937 // div/rem demand all inputs, because they don't want divide by zero.
1938 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1939 UndefElts2, Depth+1);
1940 if (TmpV) {
1941 I->setOperand(0, TmpV);
1942 MadeChange = true;
1943 }
1944
1945 UndefElts = UndefElts2;
1946 if (VWidth > InVWidth) {
1947 assert(0 && "Unimp");
1948 // If there are more elements in the result than there are in the source,
1949 // then an output element is undef if the corresponding input element is
1950 // undef.
1951 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1952 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1953 UndefElts |= 1ULL << OutIdx;
1954 } else if (VWidth < InVWidth) {
1955 assert(0 && "Unimp");
1956 // If there are more elements in the source than there are in the result,
1957 // then a result element is undef if all of the corresponding input
1958 // elements are undef.
1959 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1960 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1961 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1962 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1963 }
1964 break;
1965 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001966 case Instruction::And:
1967 case Instruction::Or:
1968 case Instruction::Xor:
1969 case Instruction::Add:
1970 case Instruction::Sub:
1971 case Instruction::Mul:
1972 // div/rem demand all inputs, because they don't want divide by zero.
1973 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1974 UndefElts, Depth+1);
1975 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1976 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1977 UndefElts2, Depth+1);
1978 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1979
1980 // Output elements are undefined if both are undefined. Consider things
1981 // like undef&0. The result is known zero, not undef.
1982 UndefElts &= UndefElts2;
1983 break;
1984
1985 case Instruction::Call: {
1986 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1987 if (!II) break;
1988 switch (II->getIntrinsicID()) {
1989 default: break;
1990
1991 // Binary vector operations that work column-wise. A dest element is a
1992 // function of the corresponding input elements from the two inputs.
1993 case Intrinsic::x86_sse_sub_ss:
1994 case Intrinsic::x86_sse_mul_ss:
1995 case Intrinsic::x86_sse_min_ss:
1996 case Intrinsic::x86_sse_max_ss:
1997 case Intrinsic::x86_sse2_sub_sd:
1998 case Intrinsic::x86_sse2_mul_sd:
1999 case Intrinsic::x86_sse2_min_sd:
2000 case Intrinsic::x86_sse2_max_sd:
2001 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2002 UndefElts, Depth+1);
2003 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2004 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2005 UndefElts2, Depth+1);
2006 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2007
2008 // If only the low elt is demanded and this is a scalarizable intrinsic,
2009 // scalarize it now.
2010 if (DemandedElts == 1) {
2011 switch (II->getIntrinsicID()) {
2012 default: break;
2013 case Intrinsic::x86_sse_sub_ss:
2014 case Intrinsic::x86_sse_mul_ss:
2015 case Intrinsic::x86_sse2_sub_sd:
2016 case Intrinsic::x86_sse2_mul_sd:
2017 // TODO: Lower MIN/MAX/ABS/etc
2018 Value *LHS = II->getOperand(1);
2019 Value *RHS = II->getOperand(2);
2020 // Extract the element as scalars.
2021 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2022 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2023
2024 switch (II->getIntrinsicID()) {
2025 default: assert(0 && "Case stmts out of sync!");
2026 case Intrinsic::x86_sse_sub_ss:
2027 case Intrinsic::x86_sse2_sub_sd:
2028 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
2029 II->getName()), *II);
2030 break;
2031 case Intrinsic::x86_sse_mul_ss:
2032 case Intrinsic::x86_sse2_mul_sd:
2033 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
2034 II->getName()), *II);
2035 break;
2036 }
2037
2038 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002039 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2040 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002041 InsertNewInstBefore(New, *II);
2042 AddSoonDeadInstToWorklist(*II, 0);
2043 return New;
2044 }
2045 }
2046
2047 // Output elements are undefined if both are undefined. Consider things
2048 // like undef&0. The result is known zero, not undef.
2049 UndefElts &= UndefElts2;
2050 break;
2051 }
2052 break;
2053 }
2054 }
2055 return MadeChange ? I : 0;
2056}
2057
Nick Lewycky455e1762007-09-06 02:40:25 +00002058/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00002059/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00002060/// @brief Determine if the icmp Predicate is true when both operands are equal
2061static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002062 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
2063 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2064 pred == ICmpInst::ICMP_SLE;
2065}
2066
Nick Lewycky455e1762007-09-06 02:40:25 +00002067/// @returns true if the specified compare instruction is
2068/// true when both operands are equal...
2069/// @brief Determine if the ICmpInst returns true when both operands are equal
2070static bool isTrueWhenEqual(ICmpInst &ICI) {
2071 return isTrueWhenEqual(ICI.getPredicate());
2072}
2073
Chris Lattner564a7272003-08-13 19:01:45 +00002074/// AssociativeOpt - Perform an optimization on an associative operator. This
2075/// function is designed to check a chain of associative operators for a
2076/// potential to apply a certain optimization. Since the optimization may be
2077/// applicable if the expression was reassociated, this checks the chain, then
2078/// reassociates the expression as necessary to expose the optimization
2079/// opportunity. This makes use of a special Functor, which must define
2080/// 'shouldApply' and 'apply' methods.
2081///
2082template<typename Functor>
2083Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2084 unsigned Opcode = Root.getOpcode();
2085 Value *LHS = Root.getOperand(0);
2086
2087 // Quick check, see if the immediate LHS matches...
2088 if (F.shouldApply(LHS))
2089 return F.apply(Root);
2090
2091 // Otherwise, if the LHS is not of the same opcode as the root, return.
2092 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002093 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002094 // Should we apply this transform to the RHS?
2095 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2096
2097 // If not to the RHS, check to see if we should apply to the LHS...
2098 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2099 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2100 ShouldApply = true;
2101 }
2102
2103 // If the functor wants to apply the optimization to the RHS of LHSI,
2104 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2105 if (ShouldApply) {
2106 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002107
Chris Lattner564a7272003-08-13 19:01:45 +00002108 // Now all of the instructions are in the current basic block, go ahead
2109 // and perform the reassociation.
2110 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2111
2112 // First move the selected RHS to the LHS of the root...
2113 Root.setOperand(0, LHSI->getOperand(1));
2114
2115 // Make what used to be the LHS of the root be the user of the root...
2116 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002117 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002118 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2119 return 0;
2120 }
Chris Lattner65725312004-04-16 18:08:07 +00002121 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002122 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002123 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2124 BasicBlock::iterator ARI = &Root; ++ARI;
2125 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2126 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002127
2128 // Now propagate the ExtraOperand down the chain of instructions until we
2129 // get to LHSI.
2130 while (TmpLHSI != LHSI) {
2131 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002132 // Move the instruction to immediately before the chain we are
2133 // constructing to avoid breaking dominance properties.
2134 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2135 BB->getInstList().insert(ARI, NextLHSI);
2136 ARI = NextLHSI;
2137
Chris Lattner564a7272003-08-13 19:01:45 +00002138 Value *NextOp = NextLHSI->getOperand(1);
2139 NextLHSI->setOperand(1, ExtraOperand);
2140 TmpLHSI = NextLHSI;
2141 ExtraOperand = NextOp;
2142 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002143
Chris Lattner564a7272003-08-13 19:01:45 +00002144 // Now that the instructions are reassociated, have the functor perform
2145 // the transformation...
2146 return F.apply(Root);
2147 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002148
Chris Lattner564a7272003-08-13 19:01:45 +00002149 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2150 }
2151 return 0;
2152}
2153
2154
2155// AddRHS - Implements: X + X --> X << 1
2156struct AddRHS {
2157 Value *RHS;
2158 AddRHS(Value *rhs) : RHS(rhs) {}
2159 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2160 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00002161 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00002162 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002163 }
2164};
2165
2166// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2167// iff C1&C2 == 0
2168struct AddMaskingAnd {
2169 Constant *C2;
2170 AddMaskingAnd(Constant *c) : C2(c) {}
2171 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002172 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002173 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002174 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002175 }
2176 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00002177 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002178 }
2179};
2180
Chris Lattner6e7ba452005-01-01 16:22:27 +00002181static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002182 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002183 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002184 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002185 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002186
Reid Spencer3da59db2006-11-27 01:05:10 +00002187 return IC->InsertNewInstBefore(CastInst::create(
2188 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002189 }
2190
Chris Lattner2eefe512004-04-09 19:05:30 +00002191 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002192 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2193 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002194
Chris Lattner2eefe512004-04-09 19:05:30 +00002195 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2196 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002197 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2198 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002199 }
2200
2201 Value *Op0 = SO, *Op1 = ConstOperand;
2202 if (!ConstIsRHS)
2203 std::swap(Op0, Op1);
2204 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002205 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2206 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002207 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2208 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
2209 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002210 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002211 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002212 abort();
2213 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002214 return IC->InsertNewInstBefore(New, I);
2215}
2216
2217// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2218// constant as the other operand, try to fold the binary operator into the
2219// select arguments. This also works for Cast instructions, which obviously do
2220// not have a second operand.
2221static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2222 InstCombiner *IC) {
2223 // Don't modify shared select instructions
2224 if (!SI->hasOneUse()) return 0;
2225 Value *TV = SI->getOperand(1);
2226 Value *FV = SI->getOperand(2);
2227
2228 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002229 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002230 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002231
Chris Lattner6e7ba452005-01-01 16:22:27 +00002232 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2233 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2234
Gabor Greif051a9502008-04-06 20:25:17 +00002235 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2236 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002237 }
2238 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002239}
2240
Chris Lattner4e998b22004-09-29 05:07:12 +00002241
2242/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2243/// node as operand #0, see if we can fold the instruction into the PHI (which
2244/// is only possible if all operands to the PHI are constants).
2245Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2246 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002247 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002248 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002249
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002250 // Check to see if all of the operands of the PHI are constants. If there is
2251 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002252 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002253 BasicBlock *NonConstBB = 0;
2254 for (unsigned i = 0; i != NumPHIValues; ++i)
2255 if (!isa<Constant>(PN->getIncomingValue(i))) {
2256 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002257 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002258 NonConstBB = PN->getIncomingBlock(i);
2259
2260 // If the incoming non-constant value is in I's block, we have an infinite
2261 // loop.
2262 if (NonConstBB == I.getParent())
2263 return 0;
2264 }
2265
2266 // If there is exactly one non-constant value, we can insert a copy of the
2267 // operation in that block. However, if this is a critical edge, we would be
2268 // inserting the computation one some other paths (e.g. inside a loop). Only
2269 // do this if the pred block is unconditionally branching into the phi block.
2270 if (NonConstBB) {
2271 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2272 if (!BI || !BI->isUnconditional()) return 0;
2273 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002274
2275 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002276 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002277 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002278 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002279 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002280
2281 // Next, add all of the operands to the PHI.
2282 if (I.getNumOperands() == 2) {
2283 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002284 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002285 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002286 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002287 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2288 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2289 else
2290 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002291 } else {
2292 assert(PN->getIncomingBlock(i) == NonConstBB);
2293 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2294 InV = BinaryOperator::create(BO->getOpcode(),
2295 PN->getIncomingValue(i), C, "phitmp",
2296 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002297 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2298 InV = CmpInst::create(CI->getOpcode(),
2299 CI->getPredicate(),
2300 PN->getIncomingValue(i), C, "phitmp",
2301 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002302 else
2303 assert(0 && "Unknown binop!");
2304
Chris Lattnerdbab3862007-03-02 21:28:56 +00002305 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002306 }
2307 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002308 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002309 } else {
2310 CastInst *CI = cast<CastInst>(&I);
2311 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002312 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002313 Value *InV;
2314 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002315 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002316 } else {
2317 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00002318 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2319 I.getType(), "phitmp",
2320 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002321 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002322 }
2323 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002324 }
2325 }
2326 return ReplaceInstUsesWith(I, NewPN);
2327}
2328
Chris Lattner2454a2e2008-01-29 06:52:45 +00002329
2330/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2331/// value is never equal to -0.0.
2332///
2333/// Note that this function will need to be revisited when we support nondefault
2334/// rounding modes!
2335///
2336static bool CannotBeNegativeZero(const Value *V) {
2337 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2338 return !CFP->getValueAPF().isNegZero();
2339
2340 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2341 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2342 if (I->getOpcode() == Instruction::Add &&
2343 isa<ConstantFP>(I->getOperand(1)) &&
2344 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2345 return true;
2346
2347 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2348 if (II->getIntrinsicID() == Intrinsic::sqrt)
2349 return CannotBeNegativeZero(II->getOperand(1));
2350
2351 if (const CallInst *CI = dyn_cast<CallInst>(I))
2352 if (const Function *F = CI->getCalledFunction()) {
2353 if (F->isDeclaration()) {
2354 switch (F->getNameLen()) {
2355 case 3: // abs(x) != -0.0
2356 if (!strcmp(F->getNameStart(), "abs")) return true;
2357 break;
2358 case 4: // abs[lf](x) != -0.0
2359 if (!strcmp(F->getNameStart(), "absf")) return true;
2360 if (!strcmp(F->getNameStart(), "absl")) return true;
2361 break;
2362 }
2363 }
2364 }
2365 }
2366
2367 return false;
2368}
2369
2370
Chris Lattner7e708292002-06-25 16:13:24 +00002371Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002372 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002373 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002374
Chris Lattner66331a42004-04-10 22:01:55 +00002375 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002376 // X + undef -> undef
2377 if (isa<UndefValue>(RHS))
2378 return ReplaceInstUsesWith(I, RHS);
2379
Chris Lattner66331a42004-04-10 22:01:55 +00002380 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002381 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002382 if (RHSC->isNullValue())
2383 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002384 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002385 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2386 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002387 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002388 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002389
Chris Lattner66331a42004-04-10 22:01:55 +00002390 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002391 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002392 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002393 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002394 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00002395 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002396
2397 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2398 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002399 if (!isa<VectorType>(I.getType())) {
2400 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2401 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2402 KnownZero, KnownOne))
2403 return &I;
2404 }
Chris Lattner66331a42004-04-10 22:01:55 +00002405 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002406
2407 if (isa<PHINode>(LHS))
2408 if (Instruction *NV = FoldOpIntoPhi(I))
2409 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002410
Chris Lattner4f637d42006-01-06 17:59:59 +00002411 ConstantInt *XorRHS = 0;
2412 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002413 if (isa<ConstantInt>(RHSC) &&
2414 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002415 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002416 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002417
Zhou Sheng4351c642007-04-02 08:20:41 +00002418 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002419 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2420 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002421 do {
2422 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002423 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2424 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002425 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2426 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002427 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002428 if (!MaskedValueIsZero(XorLHS,
2429 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002430 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002431 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002432 }
2433 }
2434 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002435 C0080Val = APIntOps::lshr(C0080Val, Size);
2436 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2437 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002438
Reid Spencer35c38852007-03-28 01:36:16 +00002439 // FIXME: This shouldn't be necessary. When the backends can handle types
2440 // with funny bit widths then this whole cascade of if statements should
2441 // be removed. It is just here to get the size of the "middle" type back
2442 // up to something that the back ends can handle.
2443 const Type *MiddleType = 0;
2444 switch (Size) {
2445 default: break;
2446 case 32: MiddleType = Type::Int32Ty; break;
2447 case 16: MiddleType = Type::Int16Ty; break;
2448 case 8: MiddleType = Type::Int8Ty; break;
2449 }
2450 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002451 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002452 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002453 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002454 }
2455 }
Chris Lattner66331a42004-04-10 22:01:55 +00002456 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002457
Chris Lattner564a7272003-08-13 19:01:45 +00002458 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002459 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002460 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002461
2462 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2463 if (RHSI->getOpcode() == Instruction::Sub)
2464 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2465 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2466 }
2467 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2468 if (LHSI->getOpcode() == Instruction::Sub)
2469 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2470 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2471 }
Robert Bocchino71698282004-07-27 21:02:21 +00002472 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002473
Chris Lattner5c4afb92002-05-08 22:46:53 +00002474 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002475 // -A + -B --> -(A + B)
2476 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002477 if (LHS->getType()->isIntOrIntVector()) {
2478 if (Value *RHSV = dyn_castNegVal(RHS)) {
2479 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2480 InsertNewInstBefore(NewAdd, I);
2481 return BinaryOperator::createNeg(NewAdd);
2482 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002483 }
2484
2485 return BinaryOperator::createSub(RHS, LHSV);
2486 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002487
2488 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002489 if (!isa<Constant>(RHS))
2490 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002491 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002492
Misha Brukmanfd939082005-04-21 23:48:37 +00002493
Chris Lattner50af16a2004-11-13 19:50:12 +00002494 ConstantInt *C2;
2495 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2496 if (X == RHS) // X*C + X --> X * (C+1)
2497 return BinaryOperator::createMul(RHS, AddOne(C2));
2498
2499 // X*C1 + X*C2 --> X * (C1+C2)
2500 ConstantInt *C1;
2501 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002502 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002503 }
2504
2505 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002506 if (dyn_castFoldableMul(RHS, C2) == LHS)
2507 return BinaryOperator::createMul(LHS, AddOne(C2));
2508
Chris Lattnere617c9e2007-01-05 02:17:46 +00002509 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002510 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2511 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002512
Chris Lattnerad3448c2003-02-18 19:57:07 +00002513
Chris Lattner564a7272003-08-13 19:01:45 +00002514 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002515 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002516 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2517 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002518
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002519 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002520 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002521 Value *W, *X, *Y, *Z;
2522 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2523 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2524 if (W != Y) {
2525 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002526 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002527 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002528 std::swap(W, X);
2529 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002530 std::swap(Y, Z);
2531 std::swap(W, X);
2532 }
2533 }
2534
2535 if (W == Y) {
2536 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2537 LHS->getName()), I);
2538 return BinaryOperator::createMul(W, NewAdd);
2539 }
2540 }
2541 }
2542
Chris Lattner6b032052003-10-02 15:11:26 +00002543 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002544 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002545 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2546 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002547
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002548 // (X & FF00) + xx00 -> (X+xx00) & FF00
2549 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002550 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002551 if (Anded == CRHS) {
2552 // See if all bits from the first bit set in the Add RHS up are included
2553 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002554 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002555
2556 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002557 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002558
2559 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002560 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002561
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002562 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2563 // Okay, the xform is safe. Insert the new add pronto.
2564 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2565 LHS->getName()), I);
2566 return BinaryOperator::createAnd(NewAdd, C2);
2567 }
2568 }
2569 }
2570
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002571 // Try to fold constant add into select arguments.
2572 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002573 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002574 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002575 }
2576
Reid Spencer1628cec2006-10-26 06:15:43 +00002577 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002578 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002579 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002580 CastInst *CI = dyn_cast<CastInst>(LHS);
2581 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002582 if (!CI) {
2583 CI = dyn_cast<CastInst>(RHS);
2584 Other = LHS;
2585 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002586 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002587 (CI->getType()->getPrimitiveSizeInBits() ==
2588 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002589 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002590 unsigned AS =
2591 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002592 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2593 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002594 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002595 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002596 }
2597 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002598
Chris Lattner42790482007-12-20 01:56:58 +00002599 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002600 {
2601 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2602 Value *Other = RHS;
2603 if (!SI) {
2604 SI = dyn_cast<SelectInst>(RHS);
2605 Other = LHS;
2606 }
Chris Lattner42790482007-12-20 01:56:58 +00002607 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002608 Value *TV = SI->getTrueValue();
2609 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002610 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002611
2612 // Can we fold the add into the argument of the select?
2613 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002614 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2615 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002616 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002617 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2618 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002619 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002620 }
2621 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002622
2623 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2624 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2625 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2626 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002627
Chris Lattner7e708292002-06-25 16:13:24 +00002628 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002629}
2630
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002631// isSignBit - Return true if the value represented by the constant only has the
2632// highest order bit set.
2633static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002634 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002635 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002636}
2637
Chris Lattner7e708292002-06-25 16:13:24 +00002638Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002639 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002640
Chris Lattner233f7dc2002-08-12 21:17:25 +00002641 if (Op0 == Op1) // sub X, X -> 0
2642 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002643
Chris Lattner233f7dc2002-08-12 21:17:25 +00002644 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002645 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002646 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002647
Chris Lattnere87597f2004-10-16 18:11:37 +00002648 if (isa<UndefValue>(Op0))
2649 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2650 if (isa<UndefValue>(Op1))
2651 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2652
Chris Lattnerd65460f2003-11-05 01:06:05 +00002653 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2654 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002655 if (C->isAllOnesValue())
2656 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002657
Chris Lattnerd65460f2003-11-05 01:06:05 +00002658 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002659 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002660 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002661 return BinaryOperator::createAdd(X, AddOne(C));
2662
Chris Lattner76b7a062007-01-15 07:02:54 +00002663 // -(X >>u 31) -> (X >>s 31)
2664 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002665 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002666 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002667 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002668 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002669 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002670 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002671 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002672 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002673 return BinaryOperator::create(Instruction::AShr,
2674 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002675 }
2676 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002677 }
2678 else if (SI->getOpcode() == Instruction::AShr) {
2679 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2680 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002681 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002682 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002683 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002684 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002685 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002686 }
2687 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002688 }
2689 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002690 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002691
2692 // Try to fold constant sub into select arguments.
2693 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002694 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002695 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002696
2697 if (isa<PHINode>(Op0))
2698 if (Instruction *NV = FoldOpIntoPhi(I))
2699 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002700 }
2701
Chris Lattner43d84d62005-04-07 16:15:25 +00002702 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2703 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002704 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002705 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002706 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002707 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002708 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002709 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2710 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2711 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002712 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002713 Op1I->getOperand(0));
2714 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002715 }
2716
Chris Lattnerfd059242003-10-15 16:48:29 +00002717 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002718 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2719 // is not used by anyone else...
2720 //
Chris Lattner0517e722004-02-02 20:09:56 +00002721 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002722 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002723 // Swap the two operands of the subexpr...
2724 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2725 Op1I->setOperand(0, IIOp1);
2726 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002727
Chris Lattnera2881962003-02-18 19:28:33 +00002728 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002729 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002730 }
2731
2732 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2733 //
2734 if (Op1I->getOpcode() == Instruction::And &&
2735 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2736 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2737
Chris Lattnerf523d062004-06-09 05:08:07 +00002738 Value *NewNot =
2739 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002740 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002741 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002742
Reid Spencerac5209e2006-10-16 23:08:08 +00002743 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002744 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002745 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002746 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002747 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002748 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002749 ConstantExpr::getNeg(DivRHS));
2750
Chris Lattnerad3448c2003-02-18 19:57:07 +00002751 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002752 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002753 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002754 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002755 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002756 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002757
2758 // X - ((X / Y) * Y) --> X % Y
2759 if (Op1I->getOpcode() == Instruction::Mul)
2760 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2761 if (Op0 == I->getOperand(0) &&
2762 Op1I->getOperand(1) == I->getOperand(1)) {
2763 if (I->getOpcode() == Instruction::SDiv)
2764 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2765 if (I->getOpcode() == Instruction::UDiv)
2766 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2767 }
Chris Lattner40371712002-05-09 01:29:19 +00002768 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002769 }
Chris Lattnera2881962003-02-18 19:28:33 +00002770
Chris Lattner9919e3d2006-12-02 00:13:08 +00002771 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002772 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002773 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002774 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2775 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2776 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2777 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002778 } else if (Op0I->getOpcode() == Instruction::Sub) {
2779 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2780 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002781 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002782 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002783
Chris Lattner50af16a2004-11-13 19:50:12 +00002784 ConstantInt *C1;
2785 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002786 if (X == Op1) // X*C - X --> X * (C-1)
2787 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002788
Chris Lattner50af16a2004-11-13 19:50:12 +00002789 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2790 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Sheng58d13af2008-02-22 10:00:35 +00002791 return BinaryOperator::createMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002792 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002793 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002794}
2795
Chris Lattnera0141b92007-07-15 20:42:37 +00002796/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2797/// comparison only checks the sign bit. If it only checks the sign bit, set
2798/// TrueIfSigned if the result of the comparison is true when the input value is
2799/// signed.
2800static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2801 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002802 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002803 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2804 TrueIfSigned = true;
2805 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002806 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2807 TrueIfSigned = true;
2808 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002809 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2810 TrueIfSigned = false;
2811 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002812 case ICmpInst::ICMP_UGT:
2813 // True if LHS u> RHS and RHS == high-bit-mask - 1
2814 TrueIfSigned = true;
2815 return RHS->getValue() ==
2816 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2817 case ICmpInst::ICMP_UGE:
2818 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2819 TrueIfSigned = true;
2820 return RHS->getValue() ==
2821 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002822 default:
2823 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002824 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002825}
2826
Chris Lattner7e708292002-06-25 16:13:24 +00002827Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002828 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002829 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002830
Chris Lattnere87597f2004-10-16 18:11:37 +00002831 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2832 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2833
Chris Lattner233f7dc2002-08-12 21:17:25 +00002834 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002835 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2836 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002837
2838 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002839 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002840 if (SI->getOpcode() == Instruction::Shl)
2841 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002842 return BinaryOperator::createMul(SI->getOperand(0),
2843 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002844
Zhou Sheng843f07672007-04-19 05:39:12 +00002845 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002846 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2847 if (CI->equalsInt(1)) // X * 1 == X
2848 return ReplaceInstUsesWith(I, Op0);
2849 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002850 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002851
Zhou Sheng97b52c22007-03-29 01:57:21 +00002852 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002853 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002854 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002855 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002856 }
Robert Bocchino71698282004-07-27 21:02:21 +00002857 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002858 if (Op1F->isNullValue())
2859 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002860
Chris Lattnera2881962003-02-18 19:28:33 +00002861 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2862 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002863 // We need a better interface for long double here.
2864 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2865 if (Op1F->isExactlyValue(1.0))
2866 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002867 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002868
2869 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2870 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2871 isa<ConstantInt>(Op0I->getOperand(1))) {
2872 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2873 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2874 Op1, "tmp");
2875 InsertNewInstBefore(Add, I);
2876 Value *C1C2 = ConstantExpr::getMul(Op1,
2877 cast<Constant>(Op0I->getOperand(1)));
2878 return BinaryOperator::createAdd(Add, C1C2);
2879
2880 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002881
2882 // Try to fold constant mul into select arguments.
2883 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002884 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002885 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002886
2887 if (isa<PHINode>(Op0))
2888 if (Instruction *NV = FoldOpIntoPhi(I))
2889 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002890 }
2891
Chris Lattnera4f445b2003-03-10 23:23:04 +00002892 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2893 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002894 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002895
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002896 // If one of the operands of the multiply is a cast from a boolean value, then
2897 // we know the bool is either zero or one, so this is a 'masking' multiply.
2898 // See if we can simplify things based on how the boolean was originally
2899 // formed.
2900 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002901 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002902 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002903 BoolCast = CI;
2904 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002905 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002906 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002907 BoolCast = CI;
2908 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002909 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002910 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2911 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002912 bool TIS = false;
2913
Reid Spencere4d87aa2006-12-23 06:05:41 +00002914 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002915 // multiply into a shift/and combination.
2916 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002917 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2918 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002919 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002920 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002921 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002922 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002923 InsertNewInstBefore(
2924 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002925 BoolCast->getOperand(0)->getName()+
2926 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002927
2928 // If the multiply type is not the same as the source type, sign extend
2929 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002930 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002931 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2932 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002933 Instruction::CastOps opcode =
2934 (SrcBits == DstBits ? Instruction::BitCast :
2935 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2936 V = InsertCastBefore(opcode, V, I.getType(), I);
2937 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002938
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002939 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002940 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002941 }
2942 }
2943 }
2944
Chris Lattner7e708292002-06-25 16:13:24 +00002945 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002946}
2947
Reid Spencer1628cec2006-10-26 06:15:43 +00002948/// This function implements the transforms on div instructions that work
2949/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2950/// used by the visitors to those instructions.
2951/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002952Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002953 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002954
Chris Lattner50b2ca42008-02-19 06:12:18 +00002955 // undef / X -> 0 for integer.
2956 // undef / X -> undef for FP (the undef could be a snan).
2957 if (isa<UndefValue>(Op0)) {
2958 if (Op0->getType()->isFPOrFPVector())
2959 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002960 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002961 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002962
2963 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002964 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002965 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002966
Chris Lattner25feae52008-01-28 00:58:18 +00002967 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2968 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002969 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002970 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2971 // the same basic block, then we replace the select with Y, and the
2972 // condition of the select with false (if the cond value is in the same BB).
2973 // If the select has uses other than the div, this allows them to be
2974 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2975 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002976 if (ST->isNullValue()) {
2977 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2978 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002979 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002980 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2981 I.setOperand(1, SI->getOperand(2));
2982 else
2983 UpdateValueUsesWith(SI, SI->getOperand(2));
2984 return &I;
2985 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002986
Chris Lattner25feae52008-01-28 00:58:18 +00002987 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2988 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002989 if (ST->isNullValue()) {
2990 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2991 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002992 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002993 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2994 I.setOperand(1, SI->getOperand(1));
2995 else
2996 UpdateValueUsesWith(SI, SI->getOperand(1));
2997 return &I;
2998 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002999 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003000
Reid Spencer1628cec2006-10-26 06:15:43 +00003001 return 0;
3002}
Misha Brukmanfd939082005-04-21 23:48:37 +00003003
Reid Spencer1628cec2006-10-26 06:15:43 +00003004/// This function implements the transforms common to both integer division
3005/// instructions (udiv and sdiv). It is called by the visitors to those integer
3006/// division instructions.
3007/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003008Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003009 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3010
3011 if (Instruction *Common = commonDivTransforms(I))
3012 return Common;
3013
3014 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3015 // div X, 1 == X
3016 if (RHS->equalsInt(1))
3017 return ReplaceInstUsesWith(I, Op0);
3018
3019 // (X / C1) / C2 -> X / (C1*C2)
3020 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3021 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3022 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003023 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3024 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3025 else
3026 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
3027 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003028 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003029
Reid Spencerbca0e382007-03-23 20:05:17 +00003030 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003031 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3032 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3033 return R;
3034 if (isa<PHINode>(Op0))
3035 if (Instruction *NV = FoldOpIntoPhi(I))
3036 return NV;
3037 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003038 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003039
Chris Lattnera2881962003-02-18 19:28:33 +00003040 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003041 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003042 if (LHS->equalsInt(0))
3043 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3044
Reid Spencer1628cec2006-10-26 06:15:43 +00003045 return 0;
3046}
3047
3048Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3049 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3050
3051 // Handle the integer div common cases
3052 if (Instruction *Common = commonIDivTransforms(I))
3053 return Common;
3054
3055 // X udiv C^2 -> X >> C
3056 // Check to see if this is an unsigned division with an exact power of 2,
3057 // if so, convert to a right shift.
3058 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003059 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00003060 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003061 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003062 }
3063
3064 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003065 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003066 if (RHSI->getOpcode() == Instruction::Shl &&
3067 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003068 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003069 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003070 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003071 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003072 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003073 Constant *C2V = ConstantInt::get(NTy, C2);
3074 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003075 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00003076 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003077 }
3078 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003079 }
3080
Reid Spencer1628cec2006-10-26 06:15:43 +00003081 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3082 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003083 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003084 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003085 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003086 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003087 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003088 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003089 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003090 // Construct the "on true" case of the select
3091 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3092 Instruction *TSI = BinaryOperator::createLShr(
3093 Op0, TC, SI->getName()+".t");
3094 TSI = InsertNewInstBefore(TSI, I);
3095
3096 // Construct the "on false" case of the select
3097 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3098 Instruction *FSI = BinaryOperator::createLShr(
3099 Op0, FC, SI->getName()+".f");
3100 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003101
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003102 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003103 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003104 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003105 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003106 return 0;
3107}
3108
Reid Spencer1628cec2006-10-26 06:15:43 +00003109Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3110 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3111
3112 // Handle the integer div common cases
3113 if (Instruction *Common = commonIDivTransforms(I))
3114 return Common;
3115
3116 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3117 // sdiv X, -1 == -X
3118 if (RHS->isAllOnesValue())
3119 return BinaryOperator::createNeg(Op0);
3120
3121 // -X/C -> X/-C
3122 if (Value *LHSNeg = dyn_castNegVal(Op0))
3123 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3124 }
3125
3126 // If the sign bits of both operands are zero (i.e. we can prove they are
3127 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003128 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003129 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003130 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003131 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00003132 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3133 }
3134 }
3135
3136 return 0;
3137}
3138
3139Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3140 return commonDivTransforms(I);
3141}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003142
Reid Spencer0a783f72006-11-02 01:53:59 +00003143/// This function implements the transforms on rem instructions that work
3144/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3145/// is used by the visitors to those instructions.
3146/// @brief Transforms common to all three rem instructions
3147Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003148 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003149
Chris Lattner50b2ca42008-02-19 06:12:18 +00003150 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003151 if (Constant *LHS = dyn_cast<Constant>(Op0))
3152 if (LHS->isNullValue())
3153 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3154
Chris Lattner50b2ca42008-02-19 06:12:18 +00003155 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3156 if (I.getType()->isFPOrFPVector())
3157 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003158 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003159 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003160 if (isa<UndefValue>(Op1))
3161 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003162
3163 // Handle cases involving: rem X, (select Cond, Y, Z)
3164 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3165 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3166 // the same basic block, then we replace the select with Y, and the
3167 // condition of the select with false (if the cond value is in the same
3168 // BB). If the select has uses other than the div, this allows them to be
3169 // simplified also.
3170 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3171 if (ST->isNullValue()) {
3172 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3173 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003174 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003175 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3176 I.setOperand(1, SI->getOperand(2));
3177 else
3178 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003179 return &I;
3180 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003181 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3182 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3183 if (ST->isNullValue()) {
3184 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3185 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003186 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003187 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3188 I.setOperand(1, SI->getOperand(1));
3189 else
3190 UpdateValueUsesWith(SI, SI->getOperand(1));
3191 return &I;
3192 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003193 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003194
Reid Spencer0a783f72006-11-02 01:53:59 +00003195 return 0;
3196}
3197
3198/// This function implements the transforms common to both integer remainder
3199/// instructions (urem and srem). It is called by the visitors to those integer
3200/// remainder instructions.
3201/// @brief Common integer remainder transforms
3202Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3203 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3204
3205 if (Instruction *common = commonRemTransforms(I))
3206 return common;
3207
Chris Lattner857e8cd2004-12-12 21:48:58 +00003208 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003209 // X % 0 == undef, we don't need to preserve faults!
3210 if (RHS->equalsInt(0))
3211 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3212
Chris Lattnera2881962003-02-18 19:28:33 +00003213 if (RHS->equalsInt(1)) // X % 1 == 0
3214 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3215
Chris Lattner97943922006-02-28 05:49:21 +00003216 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3217 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3218 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3219 return R;
3220 } else if (isa<PHINode>(Op0I)) {
3221 if (Instruction *NV = FoldOpIntoPhi(I))
3222 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003223 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003224
3225 // See if we can fold away this rem instruction.
3226 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3227 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3228 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3229 KnownZero, KnownOne))
3230 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003231 }
Chris Lattnera2881962003-02-18 19:28:33 +00003232 }
3233
Reid Spencer0a783f72006-11-02 01:53:59 +00003234 return 0;
3235}
3236
3237Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3238 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3239
3240 if (Instruction *common = commonIRemTransforms(I))
3241 return common;
3242
3243 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3244 // X urem C^2 -> X and C
3245 // Check to see if this is an unsigned remainder with an exact power of 2,
3246 // if so, convert to a bitwise and.
3247 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003248 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00003249 return BinaryOperator::createAnd(Op0, SubOne(C));
3250 }
3251
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003252 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003253 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3254 if (RHSI->getOpcode() == Instruction::Shl &&
3255 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003256 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003257 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3258 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3259 "tmp"), I);
3260 return BinaryOperator::createAnd(Op0, Add);
3261 }
3262 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003263 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003264
Reid Spencer0a783f72006-11-02 01:53:59 +00003265 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3266 // where C1&C2 are powers of two.
3267 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3268 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3269 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3270 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003271 if ((STO->getValue().isPowerOf2()) &&
3272 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003273 Value *TrueAnd = InsertNewInstBefore(
3274 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3275 Value *FalseAnd = InsertNewInstBefore(
3276 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003277 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003278 }
3279 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003280 }
3281
Chris Lattner3f5b8772002-05-06 16:14:14 +00003282 return 0;
3283}
3284
Reid Spencer0a783f72006-11-02 01:53:59 +00003285Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3286 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3287
Dan Gohmancff55092007-11-05 23:16:33 +00003288 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003289 if (Instruction *common = commonIRemTransforms(I))
3290 return common;
3291
3292 if (Value *RHSNeg = dyn_castNegVal(Op1))
3293 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003294 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003295 // X % -Y -> X % Y
3296 AddUsesToWorkList(I);
3297 I.setOperand(1, RHSNeg);
3298 return &I;
3299 }
3300
Dan Gohmancff55092007-11-05 23:16:33 +00003301 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003302 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003303 if (I.getType()->isInteger()) {
3304 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3305 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3306 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3307 return BinaryOperator::createURem(Op0, Op1, I.getName());
3308 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003309 }
3310
3311 return 0;
3312}
3313
3314Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003315 return commonRemTransforms(I);
3316}
3317
Chris Lattner8b170942002-08-09 23:47:40 +00003318// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003319static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003320 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003321 if (!isSigned)
3322 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3323 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003324}
3325
3326// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003327static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003328 if (!isSigned)
3329 return C->getValue() == 1; // unsigned
3330
3331 // Calculate 1111111111000000000000
3332 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3333 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003334}
3335
Chris Lattner457dd822004-06-09 07:59:58 +00003336// isOneBitSet - Return true if there is exactly one bit set in the specified
3337// constant.
3338static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003339 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003340}
3341
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003342// isHighOnes - Return true if the constant is of the form 1+0+.
3343// This is the same as lowones(~X).
3344static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003345 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003346}
3347
Reid Spencere4d87aa2006-12-23 06:05:41 +00003348/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003349/// are carefully arranged to allow folding of expressions such as:
3350///
3351/// (A < B) | (A > B) --> (A != B)
3352///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003353/// Note that this is only valid if the first and second predicates have the
3354/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003355///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003356/// Three bits are used to represent the condition, as follows:
3357/// 0 A > B
3358/// 1 A == B
3359/// 2 A < B
3360///
3361/// <=> Value Definition
3362/// 000 0 Always false
3363/// 001 1 A > B
3364/// 010 2 A == B
3365/// 011 3 A >= B
3366/// 100 4 A < B
3367/// 101 5 A != B
3368/// 110 6 A <= B
3369/// 111 7 Always true
3370///
3371static unsigned getICmpCode(const ICmpInst *ICI) {
3372 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003373 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003374 case ICmpInst::ICMP_UGT: return 1; // 001
3375 case ICmpInst::ICMP_SGT: return 1; // 001
3376 case ICmpInst::ICMP_EQ: return 2; // 010
3377 case ICmpInst::ICMP_UGE: return 3; // 011
3378 case ICmpInst::ICMP_SGE: return 3; // 011
3379 case ICmpInst::ICMP_ULT: return 4; // 100
3380 case ICmpInst::ICMP_SLT: return 4; // 100
3381 case ICmpInst::ICMP_NE: return 5; // 101
3382 case ICmpInst::ICMP_ULE: return 6; // 110
3383 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003384 // True -> 7
3385 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003386 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003387 return 0;
3388 }
3389}
3390
Reid Spencere4d87aa2006-12-23 06:05:41 +00003391/// getICmpValue - This is the complement of getICmpCode, which turns an
3392/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003393/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003394/// of predicate to use in new icmp instructions.
3395static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3396 switch (code) {
3397 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003398 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003399 case 1:
3400 if (sign)
3401 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3402 else
3403 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3404 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3405 case 3:
3406 if (sign)
3407 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3408 else
3409 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3410 case 4:
3411 if (sign)
3412 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3413 else
3414 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3415 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3416 case 6:
3417 if (sign)
3418 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3419 else
3420 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003421 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003422 }
3423}
3424
Reid Spencere4d87aa2006-12-23 06:05:41 +00003425static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3426 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3427 (ICmpInst::isSignedPredicate(p1) &&
3428 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3429 (ICmpInst::isSignedPredicate(p2) &&
3430 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3431}
3432
3433namespace {
3434// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3435struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003436 InstCombiner &IC;
3437 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003438 ICmpInst::Predicate pred;
3439 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3440 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3441 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003442 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003443 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3444 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003445 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3446 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003447 return false;
3448 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003449 Instruction *apply(Instruction &Log) const {
3450 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3451 if (ICI->getOperand(0) != LHS) {
3452 assert(ICI->getOperand(1) == LHS);
3453 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003454 }
3455
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003456 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003457 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003458 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003459 unsigned Code;
3460 switch (Log.getOpcode()) {
3461 case Instruction::And: Code = LHSCode & RHSCode; break;
3462 case Instruction::Or: Code = LHSCode | RHSCode; break;
3463 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003464 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003465 }
3466
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003467 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3468 ICmpInst::isSignedPredicate(ICI->getPredicate());
3469
3470 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003471 if (Instruction *I = dyn_cast<Instruction>(RV))
3472 return I;
3473 // Otherwise, it's a constant boolean value...
3474 return IC.ReplaceInstUsesWith(Log, RV);
3475 }
3476};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003477} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003478
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003479// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3480// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003481// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003482Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003483 ConstantInt *OpRHS,
3484 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003485 BinaryOperator &TheAnd) {
3486 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003487 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003488 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003489 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003490
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003491 switch (Op->getOpcode()) {
3492 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003493 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003494 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003495 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003496 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003497 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003498 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003499 }
3500 break;
3501 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003502 if (Together == AndRHS) // (X | C) & C --> C
3503 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003504
Chris Lattner6e7ba452005-01-01 16:22:27 +00003505 if (Op->hasOneUse() && Together != OpRHS) {
3506 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003507 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003508 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003509 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003510 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003511 }
3512 break;
3513 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003514 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003515 // Adding a one to a single bit bit-field should be turned into an XOR
3516 // of the bit. First thing to check is to see if this AND is with a
3517 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003518 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003519
3520 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003521 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003522 // Ok, at this point, we know that we are masking the result of the
3523 // ADD down to exactly one bit. If the constant we are adding has
3524 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003525 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003526
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003527 // Check to see if any bits below the one bit set in AndRHSV are set.
3528 if ((AddRHS & (AndRHSV-1)) == 0) {
3529 // If not, the only thing that can effect the output of the AND is
3530 // the bit specified by AndRHSV. If that bit is set, the effect of
3531 // the XOR is to toggle the bit. If it is clear, then the ADD has
3532 // no effect.
3533 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3534 TheAnd.setOperand(0, X);
3535 return &TheAnd;
3536 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003537 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003538 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003539 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003540 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003541 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003542 }
3543 }
3544 }
3545 }
3546 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003547
3548 case Instruction::Shl: {
3549 // We know that the AND will not produce any of the bits shifted in, so if
3550 // the anded constant includes them, clear them now!
3551 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003552 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003553 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003554 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3555 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003556
Zhou Sheng290bec52007-03-29 08:15:12 +00003557 if (CI->getValue() == ShlMask) {
3558 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003559 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3560 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003561 TheAnd.setOperand(1, CI);
3562 return &TheAnd;
3563 }
3564 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003565 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003566 case Instruction::LShr:
3567 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003568 // We know that the AND will not produce any of the bits shifted in, so if
3569 // the anded constant includes them, clear them now! This only applies to
3570 // unsigned shifts, because a signed shr may bring in set bits!
3571 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003572 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003573 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003574 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3575 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003576
Zhou Sheng290bec52007-03-29 08:15:12 +00003577 if (CI->getValue() == ShrMask) {
3578 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003579 return ReplaceInstUsesWith(TheAnd, Op);
3580 } else if (CI != AndRHS) {
3581 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3582 return &TheAnd;
3583 }
3584 break;
3585 }
3586 case Instruction::AShr:
3587 // Signed shr.
3588 // See if this is shifting in some sign extension, then masking it out
3589 // with an and.
3590 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003591 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003592 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003593 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3594 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003595 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003596 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003597 // Make the argument unsigned.
3598 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003599 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003600 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003601 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003602 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003603 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003604 }
3605 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003606 }
3607 return 0;
3608}
3609
Chris Lattner8b170942002-08-09 23:47:40 +00003610
Chris Lattnera96879a2004-09-29 17:40:11 +00003611/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3612/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003613/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3614/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003615/// insert new instructions.
3616Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003617 bool isSigned, bool Inside,
3618 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003619 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003620 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003621 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003622
Chris Lattnera96879a2004-09-29 17:40:11 +00003623 if (Inside) {
3624 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003625 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003626
Reid Spencere4d87aa2006-12-23 06:05:41 +00003627 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003628 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003629 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003630 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3631 return new ICmpInst(pred, V, Hi);
3632 }
3633
3634 // Emit V-Lo <u Hi-Lo
3635 Constant *NegLo = ConstantExpr::getNeg(Lo);
3636 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003637 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003638 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3639 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003640 }
3641
3642 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003643 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003644
Reid Spencere4e40032007-03-21 23:19:50 +00003645 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003646 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003647 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003648 ICmpInst::Predicate pred = (isSigned ?
3649 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3650 return new ICmpInst(pred, V, Hi);
3651 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003652
Reid Spencere4e40032007-03-21 23:19:50 +00003653 // Emit V-Lo >u Hi-1-Lo
3654 // Note that Hi has already had one subtracted from it, above.
3655 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003656 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003657 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003658 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3659 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003660}
3661
Chris Lattner7203e152005-09-18 07:22:02 +00003662// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3663// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3664// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3665// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003666static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003667 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003668 uint32_t BitWidth = Val->getType()->getBitWidth();
3669 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003670
3671 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003672 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003673 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003674 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003675 return true;
3676}
3677
Chris Lattner7203e152005-09-18 07:22:02 +00003678/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3679/// where isSub determines whether the operator is a sub. If we can fold one of
3680/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003681///
3682/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3683/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3684/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3685///
3686/// return (A +/- B).
3687///
3688Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003689 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003690 Instruction &I) {
3691 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3692 if (!LHSI || LHSI->getNumOperands() != 2 ||
3693 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3694
3695 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3696
3697 switch (LHSI->getOpcode()) {
3698 default: return 0;
3699 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003700 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003701 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003702 if ((Mask->getValue().countLeadingZeros() +
3703 Mask->getValue().countPopulation()) ==
3704 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003705 break;
3706
3707 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3708 // part, we don't need any explicit masks to take them out of A. If that
3709 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003710 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003711 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003712 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003713 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003714 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003715 break;
3716 }
3717 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003718 return 0;
3719 case Instruction::Or:
3720 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003721 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003722 if ((Mask->getValue().countLeadingZeros() +
3723 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003724 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003725 break;
3726 return 0;
3727 }
3728
3729 Instruction *New;
3730 if (isSub)
3731 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3732 else
3733 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3734 return InsertNewInstBefore(New, I);
3735}
3736
Chris Lattner7e708292002-06-25 16:13:24 +00003737Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003738 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003739 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003740
Chris Lattnere87597f2004-10-16 18:11:37 +00003741 if (isa<UndefValue>(Op1)) // X & undef -> 0
3742 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3743
Chris Lattner6e7ba452005-01-01 16:22:27 +00003744 // and X, X = X
3745 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003746 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003747
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003748 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003749 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003750 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003751 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3752 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3753 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003754 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003755 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003756 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003757 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003758 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003759 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003760 } else if (isa<ConstantAggregateZero>(Op1)) {
3761 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003762 }
3763 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003764
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003765 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003766 const APInt& AndRHSMask = AndRHS->getValue();
3767 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003768
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003769 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003770 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003771 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003772 Value *Op0LHS = Op0I->getOperand(0);
3773 Value *Op0RHS = Op0I->getOperand(1);
3774 switch (Op0I->getOpcode()) {
3775 case Instruction::Xor:
3776 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003777 // If the mask is only needed on one incoming arm, push it up.
3778 if (Op0I->hasOneUse()) {
3779 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3780 // Not masking anything out for the LHS, move to RHS.
3781 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3782 Op0RHS->getName()+".masked");
3783 InsertNewInstBefore(NewRHS, I);
3784 return BinaryOperator::create(
3785 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003786 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003787 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003788 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3789 // Not masking anything out for the RHS, move to LHS.
3790 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3791 Op0LHS->getName()+".masked");
3792 InsertNewInstBefore(NewLHS, I);
3793 return BinaryOperator::create(
3794 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3795 }
3796 }
3797
Chris Lattner6e7ba452005-01-01 16:22:27 +00003798 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003799 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003800 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3801 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3802 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3803 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3804 return BinaryOperator::createAnd(V, AndRHS);
3805 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3806 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003807 break;
3808
3809 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003810 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3811 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3812 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3813 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3814 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003815 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003816 }
3817
Chris Lattner58403262003-07-23 19:25:52 +00003818 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003819 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003820 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003821 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003822 // If this is an integer truncation or change from signed-to-unsigned, and
3823 // if the source is an and/or with immediate, transform it. This
3824 // frequently occurs for bitfield accesses.
3825 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003826 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003827 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003828 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003829 if (CastOp->getOpcode() == Instruction::And) {
3830 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003831 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3832 // This will fold the two constants together, which may allow
3833 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003834 Instruction *NewCast = CastInst::createTruncOrBitCast(
3835 CastOp->getOperand(0), I.getType(),
3836 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003837 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003838 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003839 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003840 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003841 return BinaryOperator::createAnd(NewCast, C3);
3842 } else if (CastOp->getOpcode() == Instruction::Or) {
3843 // Change: and (cast (or X, C1) to T), C2
3844 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003845 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003846 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3847 return ReplaceInstUsesWith(I, AndRHS);
3848 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003849 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003850 }
Chris Lattner06782f82003-07-23 19:36:21 +00003851 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003852
3853 // Try to fold constant and into select arguments.
3854 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003855 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003856 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003857 if (isa<PHINode>(Op0))
3858 if (Instruction *NV = FoldOpIntoPhi(I))
3859 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003860 }
3861
Chris Lattner8d969642003-03-10 23:06:50 +00003862 Value *Op0NotVal = dyn_castNotVal(Op0);
3863 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003864
Chris Lattner5b62aa72004-06-18 06:07:51 +00003865 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3866 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3867
Misha Brukmancb6267b2004-07-30 12:50:08 +00003868 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003869 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003870 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3871 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003872 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003873 return BinaryOperator::createNot(Or);
3874 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003875
3876 {
Chris Lattner003b6202007-06-15 05:58:24 +00003877 Value *A = 0, *B = 0, *C = 0, *D = 0;
3878 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003879 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3880 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003881
3882 // (A|B) & ~(A&B) -> A^B
3883 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3884 if ((A == C && B == D) || (A == D && B == C))
3885 return BinaryOperator::createXor(A, B);
3886 }
3887 }
3888
3889 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003890 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3891 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003892
3893 // ~(A&B) & (A|B) -> A^B
3894 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3895 if ((A == C && B == D) || (A == D && B == C))
3896 return BinaryOperator::createXor(A, B);
3897 }
3898 }
Chris Lattner64daab52006-04-01 08:03:55 +00003899
3900 if (Op0->hasOneUse() &&
3901 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3902 if (A == Op1) { // (A^B)&A -> A&(A^B)
3903 I.swapOperands(); // Simplify below
3904 std::swap(Op0, Op1);
3905 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3906 cast<BinaryOperator>(Op0)->swapOperands();
3907 I.swapOperands(); // Simplify below
3908 std::swap(Op0, Op1);
3909 }
3910 }
3911 if (Op1->hasOneUse() &&
3912 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3913 if (B == Op0) { // B&(A^B) -> B&(B^A)
3914 cast<BinaryOperator>(Op1)->swapOperands();
3915 std::swap(A, B);
3916 }
3917 if (A == Op0) { // A&(A^B) -> A & ~B
3918 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3919 InsertNewInstBefore(NotB, I);
3920 return BinaryOperator::createAnd(A, NotB);
3921 }
3922 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003923 }
3924
Reid Spencere4d87aa2006-12-23 06:05:41 +00003925 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3926 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3927 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003928 return R;
3929
Chris Lattner955f3312004-09-28 21:48:02 +00003930 Value *LHSVal, *RHSVal;
3931 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003932 ICmpInst::Predicate LHSCC, RHSCC;
3933 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3934 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3935 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3936 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3937 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3938 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3939 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003940 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3941
3942 // Don't try to fold ICMP_SLT + ICMP_ULT.
3943 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3944 ICmpInst::isSignedPredicate(LHSCC) ==
3945 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003946 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003947 ICmpInst::Predicate GT;
3948 if (ICmpInst::isSignedPredicate(LHSCC) ||
3949 (ICmpInst::isEquality(LHSCC) &&
3950 ICmpInst::isSignedPredicate(RHSCC)))
3951 GT = ICmpInst::ICMP_SGT;
3952 else
3953 GT = ICmpInst::ICMP_UGT;
3954
Reid Spencere4d87aa2006-12-23 06:05:41 +00003955 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3956 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003957 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003958 std::swap(LHS, RHS);
3959 std::swap(LHSCst, RHSCst);
3960 std::swap(LHSCC, RHSCC);
3961 }
3962
Reid Spencere4d87aa2006-12-23 06:05:41 +00003963 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003964 // comparing a value against two constants and and'ing the result
3965 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003966 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3967 // (from the FoldICmpLogical check above), that the two constants
3968 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003969 assert(LHSCst != RHSCst && "Compares not folded above?");
3970
3971 switch (LHSCC) {
3972 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003973 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003974 switch (RHSCC) {
3975 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003976 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3977 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3978 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003979 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003980 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3981 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3982 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003983 return ReplaceInstUsesWith(I, LHS);
3984 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003985 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003986 switch (RHSCC) {
3987 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003988 case ICmpInst::ICMP_ULT:
3989 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3990 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3991 break; // (X != 13 & X u< 15) -> no change
3992 case ICmpInst::ICMP_SLT:
3993 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3994 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3995 break; // (X != 13 & X s< 15) -> no change
3996 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3997 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3998 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003999 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004000 case ICmpInst::ICMP_NE:
4001 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004002 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4003 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4004 LHSVal->getName()+".off");
4005 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004006 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4007 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004008 }
4009 break; // (X != 13 & X != 15) -> no change
4010 }
4011 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004012 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004013 switch (RHSCC) {
4014 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004015 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4016 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004017 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004018 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4019 break;
4020 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4021 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004022 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004023 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4024 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004025 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004026 break;
4027 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004028 switch (RHSCC) {
4029 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004030 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4031 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004032 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004033 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4034 break;
4035 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4036 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004037 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004038 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4039 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004040 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004041 break;
4042 case ICmpInst::ICMP_UGT:
4043 switch (RHSCC) {
4044 default: assert(0 && "Unknown integer condition code!");
4045 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4046 return ReplaceInstUsesWith(I, LHS);
4047 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4048 return ReplaceInstUsesWith(I, RHS);
4049 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4050 break;
4051 case ICmpInst::ICMP_NE:
4052 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4053 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4054 break; // (X u> 13 & X != 15) -> no change
4055 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4056 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4057 true, I);
4058 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4059 break;
4060 }
4061 break;
4062 case ICmpInst::ICMP_SGT:
4063 switch (RHSCC) {
4064 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004065 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004066 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4067 return ReplaceInstUsesWith(I, RHS);
4068 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4069 break;
4070 case ICmpInst::ICMP_NE:
4071 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4072 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4073 break; // (X s> 13 & X != 15) -> no change
4074 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4075 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4076 true, I);
4077 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4078 break;
4079 }
4080 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004081 }
4082 }
4083 }
4084
Chris Lattner6fc205f2006-05-05 06:39:07 +00004085 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004086 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4087 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4088 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4089 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004090 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004091 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004092 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4093 I.getType(), TD) &&
4094 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4095 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004096 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4097 Op1C->getOperand(0),
4098 I.getName());
4099 InsertNewInstBefore(NewOp, I);
4100 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4101 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004102 }
Chris Lattnere511b742006-11-14 07:46:50 +00004103
4104 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004105 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4106 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4107 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004108 SI0->getOperand(1) == SI1->getOperand(1) &&
4109 (SI0->hasOneUse() || SI1->hasOneUse())) {
4110 Instruction *NewOp =
4111 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4112 SI1->getOperand(0),
4113 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004114 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4115 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004116 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004117 }
4118
Chris Lattner99c65742007-10-24 05:38:08 +00004119 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4120 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4121 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4122 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4123 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4124 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4125 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4126 // If either of the constants are nans, then the whole thing returns
4127 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004128 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004129 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4130 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4131 RHS->getOperand(0));
4132 }
4133 }
4134 }
4135
Chris Lattner7e708292002-06-25 16:13:24 +00004136 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004137}
4138
Chris Lattnerafe91a52006-06-15 19:07:26 +00004139/// CollectBSwapParts - Look to see if the specified value defines a single byte
4140/// in the result. If it does, and if the specified byte hasn't been filled in
4141/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004142static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004143 Instruction *I = dyn_cast<Instruction>(V);
4144 if (I == 0) return true;
4145
4146 // If this is an or instruction, it is an inner node of the bswap.
4147 if (I->getOpcode() == Instruction::Or)
4148 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4149 CollectBSwapParts(I->getOperand(1), ByteValues);
4150
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004151 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004152 // If this is a shift by a constant int, and it is "24", then its operand
4153 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004154 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004155 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004156 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004157 8*(ByteValues.size()-1))
4158 return true;
4159
4160 unsigned DestNo;
4161 if (I->getOpcode() == Instruction::Shl) {
4162 // X << 24 defines the top byte with the lowest of the input bytes.
4163 DestNo = ByteValues.size()-1;
4164 } else {
4165 // X >>u 24 defines the low byte with the highest of the input bytes.
4166 DestNo = 0;
4167 }
4168
4169 // If the destination byte value is already defined, the values are or'd
4170 // together, which isn't a bswap (unless it's an or of the same bits).
4171 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4172 return true;
4173 ByteValues[DestNo] = I->getOperand(0);
4174 return false;
4175 }
4176
4177 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4178 // don't have this.
4179 Value *Shift = 0, *ShiftLHS = 0;
4180 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4181 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4182 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4183 return true;
4184 Instruction *SI = cast<Instruction>(Shift);
4185
4186 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004187 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4188 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004189 return true;
4190
4191 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4192 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004193 if (AndAmt->getValue().getActiveBits() > 64)
4194 return true;
4195 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004196 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004197 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004198 break;
4199 // Unknown mask for bswap.
4200 if (DestByte == ByteValues.size()) return true;
4201
Reid Spencerb83eb642006-10-20 07:07:24 +00004202 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004203 unsigned SrcByte;
4204 if (SI->getOpcode() == Instruction::Shl)
4205 SrcByte = DestByte - ShiftBytes;
4206 else
4207 SrcByte = DestByte + ShiftBytes;
4208
4209 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4210 if (SrcByte != ByteValues.size()-DestByte-1)
4211 return true;
4212
4213 // If the destination byte value is already defined, the values are or'd
4214 // together, which isn't a bswap (unless it's an or of the same bits).
4215 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4216 return true;
4217 ByteValues[DestByte] = SI->getOperand(0);
4218 return false;
4219}
4220
4221/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4222/// If so, insert the new bswap intrinsic and return it.
4223Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004224 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4225 if (!ITy || ITy->getBitWidth() % 16)
4226 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004227
4228 /// ByteValues - For each byte of the result, we keep track of which value
4229 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004230 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004231 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004232
4233 // Try to find all the pieces corresponding to the bswap.
4234 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4235 CollectBSwapParts(I.getOperand(1), ByteValues))
4236 return 0;
4237
4238 // Check to see if all of the bytes come from the same value.
4239 Value *V = ByteValues[0];
4240 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4241
4242 // Check to make sure that all of the bytes come from the same value.
4243 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4244 if (ByteValues[i] != V)
4245 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004246 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004247 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004248 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004249 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004250}
4251
4252
Chris Lattner7e708292002-06-25 16:13:24 +00004253Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004254 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004255 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004256
Chris Lattner42593e62007-03-24 23:56:43 +00004257 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004258 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004259
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004260 // or X, X = X
4261 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004262 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004263
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004264 // See if we can simplify any instructions used by the instruction whose sole
4265 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004266 if (!isa<VectorType>(I.getType())) {
4267 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4268 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4269 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4270 KnownZero, KnownOne))
4271 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004272 } else if (isa<ConstantAggregateZero>(Op1)) {
4273 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4274 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4275 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4276 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004277 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004278
4279
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004280
Chris Lattner3f5b8772002-05-06 16:14:14 +00004281 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004282 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004283 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004284 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4285 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004286 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004287 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004288 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004289 return BinaryOperator::createAnd(Or,
4290 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004291 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004292
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004293 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4294 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +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);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004298 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004299 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004300 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004301
4302 // Try to fold constant and into select arguments.
4303 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004304 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004305 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004306 if (isa<PHINode>(Op0))
4307 if (Instruction *NV = FoldOpIntoPhi(I))
4308 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004309 }
4310
Chris Lattner4f637d42006-01-06 17:59:59 +00004311 Value *A = 0, *B = 0;
4312 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004313
4314 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4315 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4316 return ReplaceInstUsesWith(I, Op1);
4317 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4318 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4319 return ReplaceInstUsesWith(I, Op0);
4320
Chris Lattner6423d4c2006-07-10 20:25:24 +00004321 // (A | B) | C and A | (B | C) -> bswap if possible.
4322 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004323 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004324 match(Op1, m_Or(m_Value(), m_Value())) ||
4325 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4326 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004327 if (Instruction *BSwap = MatchBSwap(I))
4328 return BSwap;
4329 }
4330
Chris Lattner6e4c6492005-05-09 04:58:36 +00004331 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4332 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004333 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004334 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4335 InsertNewInstBefore(NOr, I);
4336 NOr->takeName(Op0);
4337 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004338 }
4339
4340 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4341 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004342 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004343 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4344 InsertNewInstBefore(NOr, I);
4345 NOr->takeName(Op0);
4346 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004347 }
4348
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004349 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004350 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004351 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4352 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004353 Value *V1 = 0, *V2 = 0, *V3 = 0;
4354 C1 = dyn_cast<ConstantInt>(C);
4355 C2 = dyn_cast<ConstantInt>(D);
4356 if (C1 && C2) { // (A & C1)|(B & C2)
4357 // If we have: ((V + N) & C1) | (V & C2)
4358 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4359 // replace with V+N.
4360 if (C1->getValue() == ~C2->getValue()) {
4361 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4362 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4363 // Add commutes, try both ways.
4364 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4365 return ReplaceInstUsesWith(I, A);
4366 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4367 return ReplaceInstUsesWith(I, A);
4368 }
4369 // Or commutes, try both ways.
4370 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4371 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4372 // Add commutes, try both ways.
4373 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4374 return ReplaceInstUsesWith(I, B);
4375 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4376 return ReplaceInstUsesWith(I, B);
4377 }
4378 }
Chris Lattner044e5332007-04-08 08:01:49 +00004379 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004380 }
4381
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004382 // Check to see if we have any common things being and'ed. If so, find the
4383 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004384 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4385 if (A == B) // (A & C)|(A & D) == A & (C|D)
4386 V1 = A, V2 = C, V3 = D;
4387 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4388 V1 = A, V2 = B, V3 = C;
4389 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4390 V1 = C, V2 = A, V3 = D;
4391 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4392 V1 = C, V2 = A, V3 = B;
4393
4394 if (V1) {
4395 Value *Or =
4396 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4397 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004398 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004399 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004400 }
Chris Lattnere511b742006-11-14 07:46:50 +00004401
4402 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004403 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4404 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4405 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004406 SI0->getOperand(1) == SI1->getOperand(1) &&
4407 (SI0->hasOneUse() || SI1->hasOneUse())) {
4408 Instruction *NewOp =
4409 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4410 SI1->getOperand(0),
4411 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004412 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4413 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004414 }
4415 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004416
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004417 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4418 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004419 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004420 } else {
4421 A = 0;
4422 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004423 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004424 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4425 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004426 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004427
Misha Brukmancb6267b2004-07-30 12:50:08 +00004428 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004429 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4430 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4431 I.getName()+".demorgan"), I);
4432 return BinaryOperator::createNot(And);
4433 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004434 }
Chris Lattnera2881962003-02-18 19:28:33 +00004435
Reid Spencere4d87aa2006-12-23 06:05:41 +00004436 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4437 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4438 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004439 return R;
4440
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004441 Value *LHSVal, *RHSVal;
4442 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004443 ICmpInst::Predicate LHSCC, RHSCC;
4444 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4445 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4446 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4447 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4448 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4449 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4450 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004451 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4452 // We can't fold (ugt x, C) | (sgt x, C2).
4453 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004454 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004455 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004456 bool NeedsSwap;
4457 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004458 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004459 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004460 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004461
4462 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004463 std::swap(LHS, RHS);
4464 std::swap(LHSCst, RHSCst);
4465 std::swap(LHSCC, RHSCC);
4466 }
4467
Reid Spencere4d87aa2006-12-23 06:05:41 +00004468 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004469 // comparing a value against two constants and or'ing the result
4470 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004471 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4472 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004473 // equal.
4474 assert(LHSCst != RHSCst && "Compares not folded above?");
4475
4476 switch (LHSCC) {
4477 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004478 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004479 switch (RHSCC) {
4480 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004481 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004482 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4483 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4484 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4485 LHSVal->getName()+".off");
4486 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004487 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004488 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004489 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004490 break; // (X == 13 | X == 15) -> no change
4491 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4492 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004493 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004494 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4495 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4496 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004497 return ReplaceInstUsesWith(I, RHS);
4498 }
4499 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004500 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004501 switch (RHSCC) {
4502 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004503 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4504 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4505 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004506 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004507 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4508 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4509 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004510 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004511 }
4512 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004513 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004514 switch (RHSCC) {
4515 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004516 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004517 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004518 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004519 // If RHSCst is [us]MAXINT, it is always false. Not handling
4520 // this can cause overflow.
4521 if (RHSCst->isMaxValue(false))
4522 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004523 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4524 false, I);
4525 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4526 break;
4527 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4528 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004529 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004530 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4531 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004532 }
4533 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004534 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004535 switch (RHSCC) {
4536 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004537 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4538 break;
4539 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004540 // If RHSCst is [us]MAXINT, it is always false. Not handling
4541 // this can cause overflow.
4542 if (RHSCst->isMaxValue(true))
4543 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004544 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4545 false, I);
4546 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4547 break;
4548 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4549 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4550 return ReplaceInstUsesWith(I, RHS);
4551 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4552 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004553 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004554 break;
4555 case ICmpInst::ICMP_UGT:
4556 switch (RHSCC) {
4557 default: assert(0 && "Unknown integer condition code!");
4558 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4559 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4560 return ReplaceInstUsesWith(I, LHS);
4561 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4562 break;
4563 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4564 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004565 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004566 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4567 break;
4568 }
4569 break;
4570 case ICmpInst::ICMP_SGT:
4571 switch (RHSCC) {
4572 default: assert(0 && "Unknown integer condition code!");
4573 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4574 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4575 return ReplaceInstUsesWith(I, LHS);
4576 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4577 break;
4578 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4579 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004580 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004581 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4582 break;
4583 }
4584 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004585 }
4586 }
4587 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004588
4589 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004590 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004591 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004592 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004593 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4594 !isa<ICmpInst>(Op1C->getOperand(0))) {
4595 const Type *SrcTy = Op0C->getOperand(0)->getType();
4596 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4597 // Only do this if the casts both really cause code to be
4598 // generated.
4599 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4600 I.getType(), TD) &&
4601 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4602 I.getType(), TD)) {
4603 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4604 Op1C->getOperand(0),
4605 I.getName());
4606 InsertNewInstBefore(NewOp, I);
4607 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4608 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004609 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004610 }
Chris Lattner99c65742007-10-24 05:38:08 +00004611 }
4612
4613
4614 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4615 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4616 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4617 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004618 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4619 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004620 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4621 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4622 // If either of the constants are nans, then the whole thing returns
4623 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004624 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004625 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4626
4627 // Otherwise, no need to compare the two constants, compare the
4628 // rest.
4629 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4630 RHS->getOperand(0));
4631 }
4632 }
4633 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004634
Chris Lattner7e708292002-06-25 16:13:24 +00004635 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004636}
4637
Chris Lattnerc317d392004-02-16 01:20:27 +00004638// XorSelf - Implements: X ^ X --> 0
4639struct XorSelf {
4640 Value *RHS;
4641 XorSelf(Value *rhs) : RHS(rhs) {}
4642 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4643 Instruction *apply(BinaryOperator &Xor) const {
4644 return &Xor;
4645 }
4646};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004647
4648
Chris Lattner7e708292002-06-25 16:13:24 +00004649Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004650 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004651 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004652
Evan Chengd34af782008-03-25 20:07:13 +00004653 if (isa<UndefValue>(Op1)) {
4654 if (isa<UndefValue>(Op0))
4655 // Handle undef ^ undef -> 0 special case. This is a common
4656 // idiom (misuse).
4657 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004658 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004659 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004660
Chris Lattnerc317d392004-02-16 01:20:27 +00004661 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4662 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004663 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004664 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004665 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004666
4667 // See if we can simplify any instructions used by the instruction whose sole
4668 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004669 if (!isa<VectorType>(I.getType())) {
4670 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4671 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4672 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4673 KnownZero, KnownOne))
4674 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004675 } else if (isa<ConstantAggregateZero>(Op1)) {
4676 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004677 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004678
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004679 // Is this a ~ operation?
4680 if (Value *NotOp = dyn_castNotVal(&I)) {
4681 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4682 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4683 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4684 if (Op0I->getOpcode() == Instruction::And ||
4685 Op0I->getOpcode() == Instruction::Or) {
4686 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4687 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4688 Instruction *NotY =
4689 BinaryOperator::createNot(Op0I->getOperand(1),
4690 Op0I->getOperand(1)->getName()+".not");
4691 InsertNewInstBefore(NotY, I);
4692 if (Op0I->getOpcode() == Instruction::And)
4693 return BinaryOperator::createOr(Op0NotVal, NotY);
4694 else
4695 return BinaryOperator::createAnd(Op0NotVal, NotY);
4696 }
4697 }
4698 }
4699 }
4700
4701
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004702 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004703 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4704 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4705 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004706 return new ICmpInst(ICI->getInversePredicate(),
4707 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004708
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004709 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4710 return new FCmpInst(FCI->getInversePredicate(),
4711 FCI->getOperand(0), FCI->getOperand(1));
4712 }
4713
Reid Spencere4d87aa2006-12-23 06:05:41 +00004714 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004715 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004716 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4717 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004718 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4719 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004720 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004721 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004722 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004723
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004724 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004725 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004726 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004727 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004728 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4729 return BinaryOperator::createSub(
4730 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004731 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004732 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004733 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004734 // (X + C) ^ signbit -> (X + C + signbit)
4735 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4736 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004737
Chris Lattner7c4049c2004-01-12 19:35:11 +00004738 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004739 } else if (Op0I->getOpcode() == Instruction::Or) {
4740 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004741 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004742 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4743 // Anything in both C1 and C2 is known to be zero, remove it from
4744 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004745 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004746 NewRHS = ConstantExpr::getAnd(NewRHS,
4747 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004748 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004749 I.setOperand(0, Op0I->getOperand(0));
4750 I.setOperand(1, NewRHS);
4751 return &I;
4752 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004753 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004754 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004755 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004756
4757 // Try to fold constant and into select arguments.
4758 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004759 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004760 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004761 if (isa<PHINode>(Op0))
4762 if (Instruction *NV = FoldOpIntoPhi(I))
4763 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004764 }
4765
Chris Lattner8d969642003-03-10 23:06:50 +00004766 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004767 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004768 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004769
Chris Lattner8d969642003-03-10 23:06:50 +00004770 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004771 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004772 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004773
Chris Lattner318bf792007-03-18 22:51:34 +00004774
4775 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4776 if (Op1I) {
4777 Value *A, *B;
4778 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4779 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004780 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004781 I.swapOperands();
4782 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004783 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004784 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004785 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004786 }
Chris Lattner318bf792007-03-18 22:51:34 +00004787 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4788 if (Op0 == A) // A^(A^B) == B
4789 return ReplaceInstUsesWith(I, B);
4790 else if (Op0 == B) // A^(B^A) == B
4791 return ReplaceInstUsesWith(I, A);
4792 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004793 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004794 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004795 std::swap(A, B);
4796 }
Chris Lattner318bf792007-03-18 22:51:34 +00004797 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004798 I.swapOperands(); // Simplified below.
4799 std::swap(Op0, Op1);
4800 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004801 }
Chris Lattner318bf792007-03-18 22:51:34 +00004802 }
4803
4804 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4805 if (Op0I) {
4806 Value *A, *B;
4807 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4808 if (A == Op1) // (B|A)^B == (A|B)^B
4809 std::swap(A, B);
4810 if (B == Op1) { // (A|B)^B == A & ~B
4811 Instruction *NotB =
4812 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4813 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004814 }
Chris Lattner318bf792007-03-18 22:51:34 +00004815 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4816 if (Op1 == A) // (A^B)^A == B
4817 return ReplaceInstUsesWith(I, B);
4818 else if (Op1 == B) // (B^A)^A == B
4819 return ReplaceInstUsesWith(I, A);
4820 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4821 if (A == Op1) // (A&B)^A -> (B&A)^A
4822 std::swap(A, B);
4823 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004824 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004825 Instruction *N =
4826 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004827 return BinaryOperator::createAnd(N, Op1);
4828 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004829 }
Chris Lattner318bf792007-03-18 22:51:34 +00004830 }
4831
4832 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4833 if (Op0I && Op1I && Op0I->isShift() &&
4834 Op0I->getOpcode() == Op1I->getOpcode() &&
4835 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4836 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4837 Instruction *NewOp =
4838 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4839 Op1I->getOperand(0),
4840 Op0I->getName()), I);
4841 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4842 Op1I->getOperand(1));
4843 }
4844
4845 if (Op0I && Op1I) {
4846 Value *A, *B, *C, *D;
4847 // (A & B)^(A | B) -> A ^ B
4848 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4849 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4850 if ((A == C && B == D) || (A == D && B == C))
4851 return BinaryOperator::createXor(A, B);
4852 }
4853 // (A | B)^(A & B) -> A ^ B
4854 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4855 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4856 if ((A == C && B == D) || (A == D && B == C))
4857 return BinaryOperator::createXor(A, B);
4858 }
4859
4860 // (A & B)^(C & D)
4861 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4862 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4863 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4864 // (X & Y)^(X & Y) -> (Y^Z) & X
4865 Value *X = 0, *Y = 0, *Z = 0;
4866 if (A == C)
4867 X = A, Y = B, Z = D;
4868 else if (A == D)
4869 X = A, Y = B, Z = C;
4870 else if (B == C)
4871 X = B, Y = A, Z = D;
4872 else if (B == D)
4873 X = B, Y = A, Z = C;
4874
4875 if (X) {
4876 Instruction *NewOp =
4877 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4878 return BinaryOperator::createAnd(NewOp, X);
4879 }
4880 }
4881 }
4882
Reid Spencere4d87aa2006-12-23 06:05:41 +00004883 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4884 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4885 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004886 return R;
4887
Chris Lattner6fc205f2006-05-05 06:39:07 +00004888 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004889 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004890 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004891 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4892 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004893 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004894 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004895 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4896 I.getType(), TD) &&
4897 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4898 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004899 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4900 Op1C->getOperand(0),
4901 I.getName());
4902 InsertNewInstBefore(NewOp, I);
4903 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4904 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004905 }
Chris Lattner99c65742007-10-24 05:38:08 +00004906 }
Chris Lattner7e708292002-06-25 16:13:24 +00004907 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004908}
4909
Chris Lattnera96879a2004-09-29 17:40:11 +00004910/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4911/// overflowed for this type.
4912static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004913 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004914 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004915
Reid Spencere4e40032007-03-21 23:19:50 +00004916 if (IsSigned)
4917 if (In2->getValue().isNegative())
4918 return Result->getValue().sgt(In1->getValue());
4919 else
4920 return Result->getValue().slt(In1->getValue());
4921 else
4922 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004923}
4924
Chris Lattner574da9b2005-01-13 20:14:25 +00004925/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4926/// code necessary to compute the offset from the base pointer (without adding
4927/// in the base pointer). Return the result as a signed integer of intptr size.
4928static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4929 TargetData &TD = IC.getTargetData();
4930 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004931 const Type *IntPtrTy = TD.getIntPtrType();
4932 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004933
4934 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004935 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004936 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004937
Chris Lattner574da9b2005-01-13 20:14:25 +00004938 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4939 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004940 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004941 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4942 if (OpC->isZero()) continue;
4943
4944 // Handle a struct index, which adds its field offset to the pointer.
4945 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4946 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4947
4948 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4949 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004950 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004951 Result = IC.InsertNewInstBefore(
4952 BinaryOperator::createAdd(Result,
4953 ConstantInt::get(IntPtrTy, Size),
4954 GEP->getName()+".offs"), I);
4955 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004956 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004957
4958 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4959 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4960 Scale = ConstantExpr::getMul(OC, Scale);
4961 if (Constant *RC = dyn_cast<Constant>(Result))
4962 Result = ConstantExpr::getAdd(RC, Scale);
4963 else {
4964 // Emit an add instruction.
4965 Result = IC.InsertNewInstBefore(
4966 BinaryOperator::createAdd(Result, Scale,
4967 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004968 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004969 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004970 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004971 // Convert to correct type.
4972 if (Op->getType() != IntPtrTy) {
4973 if (Constant *OpC = dyn_cast<Constant>(Op))
4974 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4975 else
4976 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4977 Op->getName()+".c"), I);
4978 }
4979 if (Size != 1) {
4980 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4981 if (Constant *OpC = dyn_cast<Constant>(Op))
4982 Op = ConstantExpr::getMul(OpC, Scale);
4983 else // We'll let instcombine(mul) convert this to a shl if possible.
4984 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4985 GEP->getName()+".idx"), I);
4986 }
4987
4988 // Emit an add instruction.
4989 if (isa<Constant>(Op) && isa<Constant>(Result))
4990 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4991 cast<Constant>(Result));
4992 else
4993 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4994 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004995 }
4996 return Result;
4997}
4998
Chris Lattner10c0d912008-04-22 02:53:33 +00004999
5000/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5001/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5002/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5003/// complex, and scales are involved. The above expression would also be legal
5004/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5005/// later form is less amenable to optimization though, and we are allowed to
5006/// generate the first by knowing that pointer arithmetic doesn't overflow.
5007///
5008/// If we can't emit an optimized form for this expression, this returns null.
5009///
5010static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5011 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005012 TargetData &TD = IC.getTargetData();
5013 gep_type_iterator GTI = gep_type_begin(GEP);
5014
5015 // Check to see if this gep only has a single variable index. If so, and if
5016 // any constant indices are a multiple of its scale, then we can compute this
5017 // in terms of the scale of the variable index. For example, if the GEP
5018 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5019 // because the expression will cross zero at the same point.
5020 unsigned i, e = GEP->getNumOperands();
5021 int64_t Offset = 0;
5022 for (i = 1; i != e; ++i, ++GTI) {
5023 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5024 // Compute the aggregate offset of constant indices.
5025 if (CI->isZero()) continue;
5026
5027 // Handle a struct index, which adds its field offset to the pointer.
5028 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5029 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5030 } else {
5031 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5032 Offset += Size*CI->getSExtValue();
5033 }
5034 } else {
5035 // Found our variable index.
5036 break;
5037 }
5038 }
5039
5040 // If there are no variable indices, we must have a constant offset, just
5041 // evaluate it the general way.
5042 if (i == e) return 0;
5043
5044 Value *VariableIdx = GEP->getOperand(i);
5045 // Determine the scale factor of the variable element. For example, this is
5046 // 4 if the variable index is into an array of i32.
5047 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5048
5049 // Verify that there are no other variable indices. If so, emit the hard way.
5050 for (++i, ++GTI; i != e; ++i, ++GTI) {
5051 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5052 if (!CI) return 0;
5053
5054 // Compute the aggregate offset of constant indices.
5055 if (CI->isZero()) continue;
5056
5057 // Handle a struct index, which adds its field offset to the pointer.
5058 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5059 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5060 } else {
5061 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5062 Offset += Size*CI->getSExtValue();
5063 }
5064 }
5065
5066 // Okay, we know we have a single variable index, which must be a
5067 // pointer/array/vector index. If there is no offset, life is simple, return
5068 // the index.
5069 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5070 if (Offset == 0) {
5071 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5072 // we don't need to bother extending: the extension won't affect where the
5073 // computation crosses zero.
5074 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5075 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5076 VariableIdx->getNameStart(), &I);
5077 return VariableIdx;
5078 }
5079
5080 // Otherwise, there is an index. The computation we will do will be modulo
5081 // the pointer size, so get it.
5082 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5083
5084 Offset &= PtrSizeMask;
5085 VariableScale &= PtrSizeMask;
5086
5087 // To do this transformation, any constant index must be a multiple of the
5088 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5089 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5090 // multiple of the variable scale.
5091 int64_t NewOffs = Offset / (int64_t)VariableScale;
5092 if (Offset != NewOffs*(int64_t)VariableScale)
5093 return 0;
5094
5095 // Okay, we can do this evaluation. Start by converting the index to intptr.
5096 const Type *IntPtrTy = TD.getIntPtrType();
5097 if (VariableIdx->getType() != IntPtrTy)
5098 VariableIdx = CastInst::createIntegerCast(VariableIdx, IntPtrTy,
5099 true /*SExt*/,
5100 VariableIdx->getNameStart(), &I);
5101 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5102 return BinaryOperator::createAdd(VariableIdx, OffsetVal, "offset", &I);
5103}
5104
5105
Reid Spencere4d87aa2006-12-23 06:05:41 +00005106/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005107/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005108Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5109 ICmpInst::Predicate Cond,
5110 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005111 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005112
Chris Lattner10c0d912008-04-22 02:53:33 +00005113 // Look through bitcasts.
5114 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5115 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005116
Chris Lattner574da9b2005-01-13 20:14:25 +00005117 Value *PtrBase = GEPLHS->getOperand(0);
5118 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005119 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005120 // This transformation (ignoring the base and scales) is valid because we
5121 // know pointers can't overflow. See if we can output an optimized form.
5122 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5123
5124 // If not, synthesize the offset the hard way.
5125 if (Offset == 0)
5126 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005127 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5128 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005129 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005130 // If the base pointers are different, but the indices are the same, just
5131 // compare the base pointer.
5132 if (PtrBase != GEPRHS->getOperand(0)) {
5133 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005134 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005135 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005136 if (IndicesTheSame)
5137 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5138 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5139 IndicesTheSame = false;
5140 break;
5141 }
5142
5143 // If all indices are the same, just compare the base pointers.
5144 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005145 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5146 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005147
5148 // Otherwise, the base pointers are different and the indices are
5149 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005150 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005151 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005152
Chris Lattnere9d782b2005-01-13 22:25:21 +00005153 // If one of the GEPs has all zero indices, recurse.
5154 bool AllZeros = true;
5155 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5156 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5157 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5158 AllZeros = false;
5159 break;
5160 }
5161 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005162 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5163 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005164
5165 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005166 AllZeros = true;
5167 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5168 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5169 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5170 AllZeros = false;
5171 break;
5172 }
5173 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005174 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005175
Chris Lattner4401c9c2005-01-14 00:20:05 +00005176 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5177 // If the GEPs only differ by one index, compare it.
5178 unsigned NumDifferences = 0; // Keep track of # differences.
5179 unsigned DiffOperand = 0; // The operand that differs.
5180 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5181 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005182 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5183 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005184 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005185 NumDifferences = 2;
5186 break;
5187 } else {
5188 if (NumDifferences++) break;
5189 DiffOperand = i;
5190 }
5191 }
5192
5193 if (NumDifferences == 0) // SAME GEP?
5194 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005195 ConstantInt::get(Type::Int1Ty,
5196 isTrueWhenEqual(Cond)));
5197
Chris Lattner4401c9c2005-01-14 00:20:05 +00005198 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005199 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5200 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005201 // Make sure we do a signed comparison here.
5202 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005203 }
5204 }
5205
Reid Spencere4d87aa2006-12-23 06:05:41 +00005206 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005207 // the result to fold to a constant!
5208 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5209 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5210 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5211 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5212 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005213 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005214 }
5215 }
5216 return 0;
5217}
5218
Reid Spencere4d87aa2006-12-23 06:05:41 +00005219Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5220 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005221 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005222
Chris Lattner58e97462007-01-14 19:42:17 +00005223 // Fold trivial predicates.
5224 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5225 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5226 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5227 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5228
5229 // Simplify 'fcmp pred X, X'
5230 if (Op0 == Op1) {
5231 switch (I.getPredicate()) {
5232 default: assert(0 && "Unknown predicate!");
5233 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5234 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5235 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5236 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5237 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5238 case FCmpInst::FCMP_OLT: // True if ordered and less than
5239 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5240 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5241
5242 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5243 case FCmpInst::FCMP_ULT: // True if unordered or less than
5244 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5245 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5246 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5247 I.setPredicate(FCmpInst::FCMP_UNO);
5248 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5249 return &I;
5250
5251 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5252 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5253 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5254 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5255 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5256 I.setPredicate(FCmpInst::FCMP_ORD);
5257 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5258 return &I;
5259 }
5260 }
5261
Reid Spencere4d87aa2006-12-23 06:05:41 +00005262 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005263 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005264
Reid Spencere4d87aa2006-12-23 06:05:41 +00005265 // Handle fcmp with constant RHS
5266 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5267 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5268 switch (LHSI->getOpcode()) {
5269 case Instruction::PHI:
5270 if (Instruction *NV = FoldOpIntoPhi(I))
5271 return NV;
5272 break;
5273 case Instruction::Select:
5274 // If either operand of the select is a constant, we can fold the
5275 // comparison into the select arms, which will cause one to be
5276 // constant folded and the select turned into a bitwise or.
5277 Value *Op1 = 0, *Op2 = 0;
5278 if (LHSI->hasOneUse()) {
5279 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5280 // Fold the known value into the constant operand.
5281 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5282 // Insert a new FCmp of the other select operand.
5283 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5284 LHSI->getOperand(2), RHSC,
5285 I.getName()), I);
5286 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5287 // Fold the known value into the constant operand.
5288 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5289 // Insert a new FCmp of the other select operand.
5290 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5291 LHSI->getOperand(1), RHSC,
5292 I.getName()), I);
5293 }
5294 }
5295
5296 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005297 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005298 break;
5299 }
5300 }
5301
5302 return Changed ? &I : 0;
5303}
5304
5305Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5306 bool Changed = SimplifyCompare(I);
5307 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5308 const Type *Ty = Op0->getType();
5309
5310 // icmp X, X
5311 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005312 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5313 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005314
5315 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005316 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005317
Reid Spencere4d87aa2006-12-23 06:05:41 +00005318 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005319 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005320 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5321 isa<ConstantPointerNull>(Op0)) &&
5322 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005323 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005324 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5325 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00005326
Reid Spencere4d87aa2006-12-23 06:05:41 +00005327 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005328 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005329 switch (I.getPredicate()) {
5330 default: assert(0 && "Invalid icmp instruction!");
5331 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00005332 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005333 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005334 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005335 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005336 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00005337 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005338
Reid Spencere4d87aa2006-12-23 06:05:41 +00005339 case ICmpInst::ICMP_UGT:
5340 case ICmpInst::ICMP_SGT:
5341 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005342 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005343 case ICmpInst::ICMP_ULT:
5344 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00005345 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5346 InsertNewInstBefore(Not, I);
5347 return BinaryOperator::createAnd(Not, Op1);
5348 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005349 case ICmpInst::ICMP_UGE:
5350 case ICmpInst::ICMP_SGE:
5351 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005352 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005353 case ICmpInst::ICMP_ULE:
5354 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00005355 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5356 InsertNewInstBefore(Not, I);
5357 return BinaryOperator::createOr(Not, Op1);
5358 }
5359 }
Chris Lattner8b170942002-08-09 23:47:40 +00005360 }
5361
Chris Lattner2be51ae2004-06-09 04:24:29 +00005362 // See if we are doing a comparison between a constant and an instruction that
5363 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005364 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005365 Value *A, *B;
5366
Chris Lattnerb6566012008-01-05 01:18:20 +00005367 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5368 if (I.isEquality() && CI->isNullValue() &&
5369 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5370 // (icmp cond A B) if cond is equality
5371 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005372 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005373
Reid Spencere4d87aa2006-12-23 06:05:41 +00005374 switch (I.getPredicate()) {
5375 default: break;
5376 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5377 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005378 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005379 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5380 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5381 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5382 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005383 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5384 if (CI->isMinValue(true))
5385 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5386 ConstantInt::getAllOnesValue(Op0->getType()));
5387
Reid Spencere4d87aa2006-12-23 06:05:41 +00005388 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005389
Reid Spencere4d87aa2006-12-23 06:05:41 +00005390 case ICmpInst::ICMP_SLT:
5391 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005392 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005393 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5394 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5395 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5396 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5397 break;
5398
5399 case ICmpInst::ICMP_UGT:
5400 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005401 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005402 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5403 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5404 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5405 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005406
5407 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5408 if (CI->isMaxValue(true))
5409 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5410 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005411 break;
5412
5413 case ICmpInst::ICMP_SGT:
5414 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005415 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005416 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5417 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5418 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5419 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5420 break;
5421
5422 case ICmpInst::ICMP_ULE:
5423 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005424 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005425 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5426 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5427 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5428 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5429 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005430
Reid Spencere4d87aa2006-12-23 06:05:41 +00005431 case ICmpInst::ICMP_SLE:
5432 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005433 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005434 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5435 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5436 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5437 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5438 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005439
Reid Spencere4d87aa2006-12-23 06:05:41 +00005440 case ICmpInst::ICMP_UGE:
5441 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005442 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005443 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5444 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5445 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5446 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5447 break;
5448
5449 case ICmpInst::ICMP_SGE:
5450 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005451 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005452 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5453 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5454 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5455 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5456 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005457 }
5458
Reid Spencere4d87aa2006-12-23 06:05:41 +00005459 // If we still have a icmp le or icmp ge instruction, turn it into the
5460 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005461 // already been handled above, this requires little checking.
5462 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005463 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005464 default: break;
5465 case ICmpInst::ICMP_ULE:
5466 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5467 case ICmpInst::ICMP_SLE:
5468 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5469 case ICmpInst::ICMP_UGE:
5470 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5471 case ICmpInst::ICMP_SGE:
5472 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005473 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005474
5475 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005476 // in the input. If this comparison is a normal comparison, it demands all
5477 // bits, if it is a sign bit comparison, it only demands the sign bit.
5478
5479 bool UnusedBit;
5480 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5481
Reid Spencer0460fb32007-03-22 20:36:03 +00005482 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5483 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005484 if (SimplifyDemandedBits(Op0,
5485 isSignBit ? APInt::getSignBit(BitWidth)
5486 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005487 KnownZero, KnownOne, 0))
5488 return &I;
5489
5490 // Given the known and unknown bits, compute a range that the LHS could be
5491 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005492 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005493 // Compute the Min, Max and RHS values based on the known bits. For the
5494 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005495 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5496 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005497 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005498 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5499 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005500 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005501 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5502 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005503 }
5504 switch (I.getPredicate()) { // LE/GE have been folded already.
5505 default: assert(0 && "Unknown icmp opcode!");
5506 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005507 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005508 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005509 break;
5510 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005511 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005512 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005513 break;
5514 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005515 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005516 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005517 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005518 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005519 break;
5520 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005521 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005522 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005523 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005524 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005525 break;
5526 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005527 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005528 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005529 if (Min.sgt(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_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005533 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005534 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005535 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005536 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005537 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005538 }
5539 }
5540
Reid Spencere4d87aa2006-12-23 06:05:41 +00005541 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005542 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005543 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005544 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005545 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5546 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005547 }
5548
Chris Lattner01deb9d2007-04-03 17:43:25 +00005549 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005550 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5551 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5552 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005553 case Instruction::GetElementPtr:
5554 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005555 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005556 bool isAllZeros = true;
5557 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5558 if (!isa<Constant>(LHSI->getOperand(i)) ||
5559 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5560 isAllZeros = false;
5561 break;
5562 }
5563 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005564 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005565 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5566 }
5567 break;
5568
Chris Lattner6970b662005-04-23 15:31:55 +00005569 case Instruction::PHI:
5570 if (Instruction *NV = FoldOpIntoPhi(I))
5571 return NV;
5572 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005573 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005574 // If either operand of the select is a constant, we can fold the
5575 // comparison into the select arms, which will cause one to be
5576 // constant folded and the select turned into a bitwise or.
5577 Value *Op1 = 0, *Op2 = 0;
5578 if (LHSI->hasOneUse()) {
5579 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5580 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005581 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5582 // Insert a new ICmp of the other select operand.
5583 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5584 LHSI->getOperand(2), RHSC,
5585 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005586 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5587 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005588 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5589 // Insert a new ICmp of the other select operand.
5590 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5591 LHSI->getOperand(1), RHSC,
5592 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005593 }
5594 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005595
Chris Lattner6970b662005-04-23 15:31:55 +00005596 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005597 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005598 break;
5599 }
Chris Lattner4802d902007-04-06 18:57:34 +00005600 case Instruction::Malloc:
5601 // If we have (malloc != null), and if the malloc has a single use, we
5602 // can assume it is successful and remove the malloc.
5603 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5604 AddToWorkList(LHSI);
5605 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5606 !isTrueWhenEqual(I)));
5607 }
5608 break;
5609 }
Chris Lattner6970b662005-04-23 15:31:55 +00005610 }
5611
Reid Spencere4d87aa2006-12-23 06:05:41 +00005612 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005613 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005614 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005615 return NI;
5616 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005617 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5618 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005619 return NI;
5620
Reid Spencere4d87aa2006-12-23 06:05:41 +00005621 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005622 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5623 // now.
5624 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5625 if (isa<PointerType>(Op0->getType()) &&
5626 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005627 // We keep moving the cast from the left operand over to the right
5628 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005629 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005630
Chris Lattner57d86372007-01-06 01:45:59 +00005631 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5632 // so eliminate it as well.
5633 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5634 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005635
Chris Lattnerde90b762003-11-03 04:25:02 +00005636 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005637 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005638 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005639 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005640 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005641 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005642 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005643 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005644 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005645 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005646 }
Chris Lattner57d86372007-01-06 01:45:59 +00005647 }
5648
5649 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005650 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005651 // This comes up when you have code like
5652 // int X = A < B;
5653 // if (X) ...
5654 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005655 // with a constant or another cast from the same type.
5656 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005657 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005658 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005659 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005660
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005661 // ~x < ~y --> y < x
5662 { Value *A, *B;
5663 if (match(Op0, m_Not(m_Value(A))) &&
5664 match(Op1, m_Not(m_Value(B))))
5665 return new ICmpInst(I.getPredicate(), B, A);
5666 }
5667
Chris Lattner65b72ba2006-09-18 04:22:48 +00005668 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005669 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005670
5671 // -x == -y --> x == y
5672 if (match(Op0, m_Neg(m_Value(A))) &&
5673 match(Op1, m_Neg(m_Value(B))))
5674 return new ICmpInst(I.getPredicate(), A, B);
5675
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005676 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5677 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5678 Value *OtherVal = A == Op1 ? B : A;
5679 return new ICmpInst(I.getPredicate(), OtherVal,
5680 Constant::getNullValue(A->getType()));
5681 }
5682
5683 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5684 // A^c1 == C^c2 --> A == C^(c1^c2)
5685 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5686 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5687 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005688 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005689 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5690 return new ICmpInst(I.getPredicate(), A,
5691 InsertNewInstBefore(Xor, I));
5692 }
5693
5694 // A^B == A^D -> B == D
5695 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5696 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5697 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5698 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5699 }
5700 }
5701
5702 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5703 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005704 // A == (A^B) -> B == 0
5705 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005706 return new ICmpInst(I.getPredicate(), OtherVal,
5707 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005708 }
5709 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005710 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005711 return new ICmpInst(I.getPredicate(), B,
5712 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005713 }
5714 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005715 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005716 return new ICmpInst(I.getPredicate(), B,
5717 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005718 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005719
Chris Lattner9c2328e2006-11-14 06:06:06 +00005720 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5721 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5722 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5723 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5724 Value *X = 0, *Y = 0, *Z = 0;
5725
5726 if (A == C) {
5727 X = B; Y = D; Z = A;
5728 } else if (A == D) {
5729 X = B; Y = C; Z = A;
5730 } else if (B == C) {
5731 X = A; Y = D; Z = B;
5732 } else if (B == D) {
5733 X = A; Y = C; Z = B;
5734 }
5735
5736 if (X) { // Build (X^Y) & Z
5737 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5738 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5739 I.setOperand(0, Op1);
5740 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5741 return &I;
5742 }
5743 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005744 }
Chris Lattner7e708292002-06-25 16:13:24 +00005745 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005746}
5747
Chris Lattner562ef782007-06-20 23:46:26 +00005748
5749/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5750/// and CmpRHS are both known to be integer constants.
5751Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5752 ConstantInt *DivRHS) {
5753 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5754 const APInt &CmpRHSV = CmpRHS->getValue();
5755
5756 // FIXME: If the operand types don't match the type of the divide
5757 // then don't attempt this transform. The code below doesn't have the
5758 // logic to deal with a signed divide and an unsigned compare (and
5759 // vice versa). This is because (x /s C1) <s C2 produces different
5760 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5761 // (x /u C1) <u C2. Simply casting the operands and result won't
5762 // work. :( The if statement below tests that condition and bails
5763 // if it finds it.
5764 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5765 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5766 return 0;
5767 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005768 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005769
5770 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5771 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5772 // C2 (CI). By solving for X we can turn this into a range check
5773 // instead of computing a divide.
5774 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5775
5776 // Determine if the product overflows by seeing if the product is
5777 // not equal to the divide. Make sure we do the same kind of divide
5778 // as in the LHS instruction that we're folding.
5779 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5780 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5781
5782 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005783 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005784
Chris Lattner1dbfd482007-06-21 18:11:19 +00005785 // Figure out the interval that is being checked. For example, a comparison
5786 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5787 // Compute this interval based on the constants involved and the signedness of
5788 // the compare/divide. This computes a half-open interval, keeping track of
5789 // whether either value in the interval overflows. After analysis each
5790 // overflow variable is set to 0 if it's corresponding bound variable is valid
5791 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5792 int LoOverflow = 0, HiOverflow = 0;
5793 ConstantInt *LoBound = 0, *HiBound = 0;
5794
5795
Chris Lattner562ef782007-06-20 23:46:26 +00005796 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005797 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005798 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005799 HiOverflow = LoOverflow = ProdOV;
5800 if (!HiOverflow)
5801 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005802 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005803 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005804 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005805 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5806 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005807 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005808 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5809 HiOverflow = LoOverflow = ProdOV;
5810 if (!HiOverflow)
5811 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005812 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005813 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005814 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5815 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005816 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005817 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005818 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005819 }
Dan Gohman76491272008-02-13 22:09:18 +00005820 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005821 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005822 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005823 LoBound = AddOne(DivRHS);
5824 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005825 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5826 HiOverflow = 1; // [INTMIN+1, overflow)
5827 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5828 }
Dan Gohman76491272008-02-13 22:09:18 +00005829 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005830 // e.g. X/-5 op 3 --> [-19, -14)
5831 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005832 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005833 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005834 HiBound = AddOne(Prod);
5835 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005836 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005837 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005838 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005839 HiBound = Subtract(Prod, DivRHS);
5840 }
5841
Chris Lattner1dbfd482007-06-21 18:11:19 +00005842 // Dividing by a negative swaps the condition. LT <-> GT
5843 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005844 }
5845
5846 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005847 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005848 default: assert(0 && "Unhandled icmp opcode!");
5849 case ICmpInst::ICMP_EQ:
5850 if (LoOverflow && HiOverflow)
5851 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5852 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005853 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005854 ICmpInst::ICMP_UGE, X, LoBound);
5855 else if (LoOverflow)
5856 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5857 ICmpInst::ICMP_ULT, X, HiBound);
5858 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005859 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005860 case ICmpInst::ICMP_NE:
5861 if (LoOverflow && HiOverflow)
5862 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5863 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005864 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005865 ICmpInst::ICMP_ULT, X, LoBound);
5866 else if (LoOverflow)
5867 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5868 ICmpInst::ICMP_UGE, X, HiBound);
5869 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005870 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005871 case ICmpInst::ICMP_ULT:
5872 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005873 if (LoOverflow == +1) // Low bound is greater than input range.
5874 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5875 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005876 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005877 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005878 case ICmpInst::ICMP_UGT:
5879 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005880 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005881 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005882 else if (HiOverflow == -1) // High bound less than input range.
5883 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5884 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005885 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5886 else
5887 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5888 }
5889}
5890
5891
Chris Lattner01deb9d2007-04-03 17:43:25 +00005892/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5893///
5894Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5895 Instruction *LHSI,
5896 ConstantInt *RHS) {
5897 const APInt &RHSV = RHS->getValue();
5898
5899 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005900 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005901 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5902 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5903 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005904 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5905 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005906 Value *CompareVal = LHSI->getOperand(0);
5907
5908 // If the sign bit of the XorCST is not set, there is no change to
5909 // the operation, just stop using the Xor.
5910 if (!XorCST->getValue().isNegative()) {
5911 ICI.setOperand(0, CompareVal);
5912 AddToWorkList(LHSI);
5913 return &ICI;
5914 }
5915
5916 // Was the old condition true if the operand is positive?
5917 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5918
5919 // If so, the new one isn't.
5920 isTrueIfPositive ^= true;
5921
5922 if (isTrueIfPositive)
5923 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5924 else
5925 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5926 }
5927 }
5928 break;
5929 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5930 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5931 LHSI->getOperand(0)->hasOneUse()) {
5932 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5933
5934 // If the LHS is an AND of a truncating cast, we can widen the
5935 // and/compare to be the input width without changing the value
5936 // produced, eliminating a cast.
5937 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5938 // We can do this transformation if either the AND constant does not
5939 // have its sign bit set or if it is an equality comparison.
5940 // Extending a relational comparison when we're checking the sign
5941 // bit would not work.
5942 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005943 (ICI.isEquality() ||
5944 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005945 uint32_t BitWidth =
5946 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5947 APInt NewCST = AndCST->getValue();
5948 NewCST.zext(BitWidth);
5949 APInt NewCI = RHSV;
5950 NewCI.zext(BitWidth);
5951 Instruction *NewAnd =
5952 BinaryOperator::createAnd(Cast->getOperand(0),
5953 ConstantInt::get(NewCST),LHSI->getName());
5954 InsertNewInstBefore(NewAnd, ICI);
5955 return new ICmpInst(ICI.getPredicate(), NewAnd,
5956 ConstantInt::get(NewCI));
5957 }
5958 }
5959
5960 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5961 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5962 // happens a LOT in code produced by the C front-end, for bitfield
5963 // access.
5964 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5965 if (Shift && !Shift->isShift())
5966 Shift = 0;
5967
5968 ConstantInt *ShAmt;
5969 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5970 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5971 const Type *AndTy = AndCST->getType(); // Type of the and.
5972
5973 // We can fold this as long as we can't shift unknown bits
5974 // into the mask. This can only happen with signed shift
5975 // rights, as they sign-extend.
5976 if (ShAmt) {
5977 bool CanFold = Shift->isLogicalShift();
5978 if (!CanFold) {
5979 // To test for the bad case of the signed shr, see if any
5980 // of the bits shifted in could be tested after the mask.
5981 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5982 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5983
5984 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5985 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5986 AndCST->getValue()) == 0)
5987 CanFold = true;
5988 }
5989
5990 if (CanFold) {
5991 Constant *NewCst;
5992 if (Shift->getOpcode() == Instruction::Shl)
5993 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5994 else
5995 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5996
5997 // Check to see if we are shifting out any of the bits being
5998 // compared.
5999 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6000 // If we shifted bits out, the fold is not going to work out.
6001 // As a special case, check to see if this means that the
6002 // result is always true or false now.
6003 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6004 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6005 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6006 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6007 } else {
6008 ICI.setOperand(1, NewCst);
6009 Constant *NewAndCST;
6010 if (Shift->getOpcode() == Instruction::Shl)
6011 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6012 else
6013 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6014 LHSI->setOperand(1, NewAndCST);
6015 LHSI->setOperand(0, Shift->getOperand(0));
6016 AddToWorkList(Shift); // Shift is dead.
6017 AddUsesToWorkList(ICI);
6018 return &ICI;
6019 }
6020 }
6021 }
6022
6023 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6024 // preferable because it allows the C<<Y expression to be hoisted out
6025 // of a loop if Y is invariant and X is not.
6026 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6027 ICI.isEquality() && !Shift->isArithmeticShift() &&
6028 isa<Instruction>(Shift->getOperand(0))) {
6029 // Compute C << Y.
6030 Value *NS;
6031 if (Shift->getOpcode() == Instruction::LShr) {
6032 NS = BinaryOperator::createShl(AndCST,
6033 Shift->getOperand(1), "tmp");
6034 } else {
6035 // Insert a logical shift.
6036 NS = BinaryOperator::createLShr(AndCST,
6037 Shift->getOperand(1), "tmp");
6038 }
6039 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6040
6041 // Compute X & (C << Y).
6042 Instruction *NewAnd =
6043 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
6044 InsertNewInstBefore(NewAnd, ICI);
6045
6046 ICI.setOperand(0, NewAnd);
6047 return &ICI;
6048 }
6049 }
6050 break;
6051
Chris Lattnera0141b92007-07-15 20:42:37 +00006052 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6053 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6054 if (!ShAmt) break;
6055
6056 uint32_t TypeBits = RHSV.getBitWidth();
6057
6058 // Check that the shift amount is in range. If not, don't perform
6059 // undefined shifts. When the shift is visited it will be
6060 // simplified.
6061 if (ShAmt->uge(TypeBits))
6062 break;
6063
6064 if (ICI.isEquality()) {
6065 // If we are comparing against bits always shifted out, the
6066 // comparison cannot succeed.
6067 Constant *Comp =
6068 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6069 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6070 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6071 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6072 return ReplaceInstUsesWith(ICI, Cst);
6073 }
6074
6075 if (LHSI->hasOneUse()) {
6076 // Otherwise strength reduce the shift into an and.
6077 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6078 Constant *Mask =
6079 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006080
Chris Lattnera0141b92007-07-15 20:42:37 +00006081 Instruction *AndI =
6082 BinaryOperator::createAnd(LHSI->getOperand(0),
6083 Mask, LHSI->getName()+".mask");
6084 Value *And = InsertNewInstBefore(AndI, ICI);
6085 return new ICmpInst(ICI.getPredicate(), And,
6086 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006087 }
6088 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006089
6090 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6091 bool TrueIfSigned = false;
6092 if (LHSI->hasOneUse() &&
6093 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6094 // (X << 31) <s 0 --> (X&1) != 0
6095 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6096 (TypeBits-ShAmt->getZExtValue()-1));
6097 Instruction *AndI =
6098 BinaryOperator::createAnd(LHSI->getOperand(0),
6099 Mask, LHSI->getName()+".mask");
6100 Value *And = InsertNewInstBefore(AndI, ICI);
6101
6102 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6103 And, Constant::getNullValue(And->getType()));
6104 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006105 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006106 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006107
6108 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006109 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006110 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006111 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006112 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006113
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006114 // Check that the shift amount is in range. If not, don't perform
6115 // undefined shifts. When the shift is visited it will be
6116 // simplified.
6117 uint32_t TypeBits = RHSV.getBitWidth();
6118 if (ShAmt->uge(TypeBits))
6119 break;
6120
6121 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006122
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006123 // If we are comparing against bits always shifted out, the
6124 // comparison cannot succeed.
6125 APInt Comp = RHSV << ShAmtVal;
6126 if (LHSI->getOpcode() == Instruction::LShr)
6127 Comp = Comp.lshr(ShAmtVal);
6128 else
6129 Comp = Comp.ashr(ShAmtVal);
6130
6131 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6132 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6133 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6134 return ReplaceInstUsesWith(ICI, Cst);
6135 }
6136
6137 // Otherwise, check to see if the bits shifted out are known to be zero.
6138 // If so, we can compare against the unshifted value:
6139 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006140 if (LHSI->hasOneUse() &&
6141 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006142 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6143 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6144 ConstantExpr::getShl(RHS, ShAmt));
6145 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006146
Evan Chengf30752c2008-04-23 00:38:06 +00006147 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006148 // Otherwise strength reduce the shift into an and.
6149 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6150 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006151
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006152 Instruction *AndI =
6153 BinaryOperator::createAnd(LHSI->getOperand(0),
6154 Mask, LHSI->getName()+".mask");
6155 Value *And = InsertNewInstBefore(AndI, ICI);
6156 return new ICmpInst(ICI.getPredicate(), And,
6157 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006158 }
6159 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006160 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006161
6162 case Instruction::SDiv:
6163 case Instruction::UDiv:
6164 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6165 // Fold this div into the comparison, producing a range check.
6166 // Determine, based on the divide type, what the range is being
6167 // checked. If there is an overflow on the low or high side, remember
6168 // it, otherwise compute the range [low, hi) bounding the new value.
6169 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006170 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6171 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6172 DivRHS))
6173 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006174 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006175
6176 case Instruction::Add:
6177 // Fold: icmp pred (add, X, C1), C2
6178
6179 if (!ICI.isEquality()) {
6180 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6181 if (!LHSC) break;
6182 const APInt &LHSV = LHSC->getValue();
6183
6184 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6185 .subtract(LHSV);
6186
6187 if (ICI.isSignedPredicate()) {
6188 if (CR.getLower().isSignBit()) {
6189 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6190 ConstantInt::get(CR.getUpper()));
6191 } else if (CR.getUpper().isSignBit()) {
6192 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6193 ConstantInt::get(CR.getLower()));
6194 }
6195 } else {
6196 if (CR.getLower().isMinValue()) {
6197 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6198 ConstantInt::get(CR.getUpper()));
6199 } else if (CR.getUpper().isMinValue()) {
6200 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6201 ConstantInt::get(CR.getLower()));
6202 }
6203 }
6204 }
6205 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006206 }
6207
6208 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6209 if (ICI.isEquality()) {
6210 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6211
6212 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6213 // the second operand is a constant, simplify a bit.
6214 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6215 switch (BO->getOpcode()) {
6216 case Instruction::SRem:
6217 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6218 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6219 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6220 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6221 Instruction *NewRem =
6222 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
6223 BO->getName());
6224 InsertNewInstBefore(NewRem, ICI);
6225 return new ICmpInst(ICI.getPredicate(), NewRem,
6226 Constant::getNullValue(BO->getType()));
6227 }
6228 }
6229 break;
6230 case Instruction::Add:
6231 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6232 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6233 if (BO->hasOneUse())
6234 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6235 Subtract(RHS, BOp1C));
6236 } else if (RHSV == 0) {
6237 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6238 // efficiently invertible, or if the add has just this one use.
6239 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6240
6241 if (Value *NegVal = dyn_castNegVal(BOp1))
6242 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6243 else if (Value *NegVal = dyn_castNegVal(BOp0))
6244 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6245 else if (BO->hasOneUse()) {
6246 Instruction *Neg = BinaryOperator::createNeg(BOp1);
6247 InsertNewInstBefore(Neg, ICI);
6248 Neg->takeName(BO);
6249 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6250 }
6251 }
6252 break;
6253 case Instruction::Xor:
6254 // For the xor case, we can xor two constants together, eliminating
6255 // the explicit xor.
6256 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6257 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6258 ConstantExpr::getXor(RHS, BOC));
6259
6260 // FALLTHROUGH
6261 case Instruction::Sub:
6262 // Replace (([sub|xor] A, B) != 0) with (A != B)
6263 if (RHSV == 0)
6264 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6265 BO->getOperand(1));
6266 break;
6267
6268 case Instruction::Or:
6269 // If bits are being or'd in that are not present in the constant we
6270 // are comparing against, then the comparison could never succeed!
6271 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6272 Constant *NotCI = ConstantExpr::getNot(RHS);
6273 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6274 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6275 isICMP_NE));
6276 }
6277 break;
6278
6279 case Instruction::And:
6280 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6281 // If bits are being compared against that are and'd out, then the
6282 // comparison can never succeed!
6283 if ((RHSV & ~BOC->getValue()) != 0)
6284 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6285 isICMP_NE));
6286
6287 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6288 if (RHS == BOC && RHSV.isPowerOf2())
6289 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6290 ICmpInst::ICMP_NE, LHSI,
6291 Constant::getNullValue(RHS->getType()));
6292
6293 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6294 if (isSignBit(BOC)) {
6295 Value *X = BO->getOperand(0);
6296 Constant *Zero = Constant::getNullValue(X->getType());
6297 ICmpInst::Predicate pred = isICMP_NE ?
6298 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6299 return new ICmpInst(pred, X, Zero);
6300 }
6301
6302 // ((X & ~7) == 0) --> X < 8
6303 if (RHSV == 0 && isHighOnes(BOC)) {
6304 Value *X = BO->getOperand(0);
6305 Constant *NegX = ConstantExpr::getNeg(BOC);
6306 ICmpInst::Predicate pred = isICMP_NE ?
6307 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6308 return new ICmpInst(pred, X, NegX);
6309 }
6310 }
6311 default: break;
6312 }
6313 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6314 // Handle icmp {eq|ne} <intrinsic>, intcst.
6315 if (II->getIntrinsicID() == Intrinsic::bswap) {
6316 AddToWorkList(II);
6317 ICI.setOperand(0, II->getOperand(1));
6318 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6319 return &ICI;
6320 }
6321 }
6322 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006323 // If the LHS is a cast from an integral value of the same size,
6324 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006325 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6326 Value *CastOp = Cast->getOperand(0);
6327 const Type *SrcTy = CastOp->getType();
6328 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6329 if (SrcTy->isInteger() &&
6330 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6331 // If this is an unsigned comparison, try to make the comparison use
6332 // smaller constant values.
6333 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6334 // X u< 128 => X s> -1
6335 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6336 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6337 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6338 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6339 // X u> 127 => X s< 0
6340 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6341 Constant::getNullValue(SrcTy));
6342 }
6343 }
6344 }
6345 }
6346 return 0;
6347}
6348
6349/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6350/// We only handle extending casts so far.
6351///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006352Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6353 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006354 Value *LHSCIOp = LHSCI->getOperand(0);
6355 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006356 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006357 Value *RHSCIOp;
6358
Chris Lattner8c756c12007-05-05 22:41:33 +00006359 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6360 // integer type is the same size as the pointer type.
6361 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6362 getTargetData().getPointerSizeInBits() ==
6363 cast<IntegerType>(DestTy)->getBitWidth()) {
6364 Value *RHSOp = 0;
6365 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006366 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006367 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6368 RHSOp = RHSC->getOperand(0);
6369 // If the pointer types don't match, insert a bitcast.
6370 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006371 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006372 }
6373
6374 if (RHSOp)
6375 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6376 }
6377
6378 // The code below only handles extension cast instructions, so far.
6379 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006380 if (LHSCI->getOpcode() != Instruction::ZExt &&
6381 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006382 return 0;
6383
Reid Spencere4d87aa2006-12-23 06:05:41 +00006384 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6385 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006386
Reid Spencere4d87aa2006-12-23 06:05:41 +00006387 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006388 // Not an extension from the same type?
6389 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006390 if (RHSCIOp->getType() != LHSCIOp->getType())
6391 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006392
Nick Lewycky4189a532008-01-28 03:48:02 +00006393 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006394 // and the other is a zext), then we can't handle this.
6395 if (CI->getOpcode() != LHSCI->getOpcode())
6396 return 0;
6397
Nick Lewycky4189a532008-01-28 03:48:02 +00006398 // Deal with equality cases early.
6399 if (ICI.isEquality())
6400 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6401
6402 // A signed comparison of sign extended values simplifies into a
6403 // signed comparison.
6404 if (isSignedCmp && isSignedExt)
6405 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6406
6407 // The other three cases all fold into an unsigned comparison.
6408 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006409 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006410
Reid Spencere4d87aa2006-12-23 06:05:41 +00006411 // If we aren't dealing with a constant on the RHS, exit early
6412 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6413 if (!CI)
6414 return 0;
6415
6416 // Compute the constant that would happen if we truncated to SrcTy then
6417 // reextended to DestTy.
6418 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6419 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6420
6421 // If the re-extended constant didn't change...
6422 if (Res2 == CI) {
6423 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6424 // For example, we might have:
6425 // %A = sext short %X to uint
6426 // %B = icmp ugt uint %A, 1330
6427 // It is incorrect to transform this into
6428 // %B = icmp ugt short %X, 1330
6429 // because %A may have negative value.
6430 //
6431 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6432 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006433 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006434 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6435 else
6436 return 0;
6437 }
6438
6439 // The re-extended constant changed so the constant cannot be represented
6440 // in the shorter type. Consequently, we cannot emit a simple comparison.
6441
6442 // First, handle some easy cases. We know the result cannot be equal at this
6443 // point so handle the ICI.isEquality() cases
6444 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006445 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006446 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006447 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006448
6449 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6450 // should have been folded away previously and not enter in here.
6451 Value *Result;
6452 if (isSignedCmp) {
6453 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006454 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006455 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006456 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006457 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006458 } else {
6459 // We're performing an unsigned comparison.
6460 if (isSignedExt) {
6461 // We're performing an unsigned comp with a sign extended value.
6462 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006463 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006464 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6465 NegOne, ICI.getName()), ICI);
6466 } else {
6467 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006468 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006469 }
6470 }
6471
6472 // Finally, return the value computed.
6473 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6474 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6475 return ReplaceInstUsesWith(ICI, Result);
6476 } else {
6477 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6478 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6479 "ICmp should be folded!");
6480 if (Constant *CI = dyn_cast<Constant>(Result))
6481 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6482 else
6483 return BinaryOperator::createNot(Result);
6484 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006485}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006486
Reid Spencer832254e2007-02-02 02:16:23 +00006487Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6488 return commonShiftTransforms(I);
6489}
6490
6491Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6492 return commonShiftTransforms(I);
6493}
6494
6495Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006496 if (Instruction *R = commonShiftTransforms(I))
6497 return R;
6498
6499 Value *Op0 = I.getOperand(0);
6500
6501 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6502 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6503 if (CSI->isAllOnesValue())
6504 return ReplaceInstUsesWith(I, CSI);
6505
6506 // See if we can turn a signed shr into an unsigned shr.
6507 if (MaskedValueIsZero(Op0,
6508 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6509 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6510
6511 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006512}
6513
6514Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6515 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006516 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006517
6518 // shl X, 0 == X and shr X, 0 == X
6519 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006520 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006521 Op0 == Constant::getNullValue(Op0->getType()))
6522 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006523
Reid Spencere4d87aa2006-12-23 06:05:41 +00006524 if (isa<UndefValue>(Op0)) {
6525 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006526 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006527 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006528 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6529 }
6530 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006531 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6532 return ReplaceInstUsesWith(I, Op0);
6533 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006534 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006535 }
6536
Chris Lattner2eefe512004-04-09 19:05:30 +00006537 // Try to fold constant and into select arguments.
6538 if (isa<Constant>(Op0))
6539 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006540 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006541 return R;
6542
Reid Spencerb83eb642006-10-20 07:07:24 +00006543 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006544 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6545 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006546 return 0;
6547}
6548
Reid Spencerb83eb642006-10-20 07:07:24 +00006549Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006550 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006551 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006552
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006553 // See if we can simplify any instructions used by the instruction whose sole
6554 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006555 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6556 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6557 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006558 KnownZero, KnownOne))
6559 return &I;
6560
Chris Lattner4d5542c2006-01-06 07:12:35 +00006561 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6562 // of a signed value.
6563 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006564 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006565 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006566 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6567 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006568 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006569 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006570 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006571 }
6572
6573 // ((X*C1) << C2) == (X * (C1 << C2))
6574 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6575 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6576 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6577 return BinaryOperator::createMul(BO->getOperand(0),
6578 ConstantExpr::getShl(BOOp, Op1));
6579
6580 // Try to fold constant and into select arguments.
6581 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6582 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6583 return R;
6584 if (isa<PHINode>(Op0))
6585 if (Instruction *NV = FoldOpIntoPhi(I))
6586 return NV;
6587
Chris Lattner8999dd32007-12-22 09:07:47 +00006588 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6589 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6590 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6591 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6592 // place. Don't try to do this transformation in this case. Also, we
6593 // require that the input operand is a shift-by-constant so that we have
6594 // confidence that the shifts will get folded together. We could do this
6595 // xform in more cases, but it is unlikely to be profitable.
6596 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6597 isa<ConstantInt>(TrOp->getOperand(1))) {
6598 // Okay, we'll do this xform. Make the shift of shift.
6599 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6600 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6601 I.getName());
6602 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6603
6604 // For logical shifts, the truncation has the effect of making the high
6605 // part of the register be zeros. Emulate this by inserting an AND to
6606 // clear the top bits as needed. This 'and' will usually be zapped by
6607 // other xforms later if dead.
6608 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6609 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6610 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6611
6612 // The mask we constructed says what the trunc would do if occurring
6613 // between the shifts. We want to know the effect *after* the second
6614 // shift. We know that it is a logical shift by a constant, so adjust the
6615 // mask as appropriate.
6616 if (I.getOpcode() == Instruction::Shl)
6617 MaskV <<= Op1->getZExtValue();
6618 else {
6619 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6620 MaskV = MaskV.lshr(Op1->getZExtValue());
6621 }
6622
6623 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6624 TI->getName());
6625 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6626
6627 // Return the value truncated to the interesting size.
6628 return new TruncInst(And, I.getType());
6629 }
6630 }
6631
Chris Lattner4d5542c2006-01-06 07:12:35 +00006632 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006633 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6634 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6635 Value *V1, *V2;
6636 ConstantInt *CC;
6637 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006638 default: break;
6639 case Instruction::Add:
6640 case Instruction::And:
6641 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006642 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006643 // These operators commute.
6644 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006645 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6646 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006647 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006648 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006649 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006650 Op0BO->getName());
6651 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006652 Instruction *X =
6653 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6654 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006655 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006656 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006657 return BinaryOperator::createAnd(X, ConstantInt::get(
6658 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006659 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006660
Chris Lattner150f12a2005-09-18 06:30:59 +00006661 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006662 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006663 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006664 match(Op0BOOp1,
6665 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006666 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6667 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006668 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006669 Op0BO->getOperand(0), Op1,
6670 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006671 InsertNewInstBefore(YS, I); // (Y << C)
6672 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006673 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006674 V1->getName()+".mask");
6675 InsertNewInstBefore(XM, I); // X & (CC << C)
6676
6677 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6678 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006679 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006680
Reid Spencera07cb7d2007-02-02 14:41:37 +00006681 // FALL THROUGH.
6682 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006683 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006684 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6685 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006686 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006687 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006688 Op0BO->getOperand(1), Op1,
6689 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006690 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006691 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006692 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006693 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006694 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006695 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006696 return BinaryOperator::createAnd(X, ConstantInt::get(
6697 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006698 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006699
Chris Lattner13d4ab42006-05-31 21:14:00 +00006700 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006701 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6702 match(Op0BO->getOperand(0),
6703 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006704 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006705 cast<BinaryOperator>(Op0BO->getOperand(0))
6706 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006707 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006708 Op0BO->getOperand(1), Op1,
6709 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006710 InsertNewInstBefore(YS, I); // (Y << C)
6711 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006712 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006713 V1->getName()+".mask");
6714 InsertNewInstBefore(XM, I); // X & (CC << C)
6715
Chris Lattner13d4ab42006-05-31 21:14:00 +00006716 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006717 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006718
Chris Lattner11021cb2005-09-18 05:12:10 +00006719 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006720 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006721 }
6722
6723
6724 // If the operand is an bitwise operator with a constant RHS, and the
6725 // shift is the only use, we can pull it out of the shift.
6726 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6727 bool isValid = true; // Valid only for And, Or, Xor
6728 bool highBitSet = false; // Transform if high bit of constant set?
6729
6730 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006731 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006732 case Instruction::Add:
6733 isValid = isLeftShift;
6734 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006735 case Instruction::Or:
6736 case Instruction::Xor:
6737 highBitSet = false;
6738 break;
6739 case Instruction::And:
6740 highBitSet = true;
6741 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006742 }
6743
6744 // If this is a signed shift right, and the high bit is modified
6745 // by the logical operation, do not perform the transformation.
6746 // The highBitSet boolean indicates the value of the high bit of
6747 // the constant which would cause it to be modified for this
6748 // operation.
6749 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006750 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006751 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006752
6753 if (isValid) {
6754 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6755
6756 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006757 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006758 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006759 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006760
6761 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6762 NewRHS);
6763 }
6764 }
6765 }
6766 }
6767
Chris Lattnerad0124c2006-01-06 07:52:12 +00006768 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006769 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6770 if (ShiftOp && !ShiftOp->isShift())
6771 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006772
Reid Spencerb83eb642006-10-20 07:07:24 +00006773 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006774 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006775 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6776 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006777 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6778 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6779 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006780
Zhou Sheng4351c642007-04-02 08:20:41 +00006781 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006782 if (AmtSum > TypeBits)
6783 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006784
6785 const IntegerType *Ty = cast<IntegerType>(I.getType());
6786
6787 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006788 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006789 return BinaryOperator::create(I.getOpcode(), X,
6790 ConstantInt::get(Ty, AmtSum));
6791 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6792 I.getOpcode() == Instruction::AShr) {
6793 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6794 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6795 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6796 I.getOpcode() == Instruction::LShr) {
6797 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6798 Instruction *Shift =
6799 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6800 InsertNewInstBefore(Shift, I);
6801
Zhou Shenge9e03f62007-03-28 15:02:20 +00006802 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006803 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006804 }
6805
Chris Lattnerb87056f2007-02-05 00:57:54 +00006806 // Okay, if we get here, one shift must be left, and the other shift must be
6807 // right. See if the amounts are equal.
6808 if (ShiftAmt1 == ShiftAmt2) {
6809 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6810 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006811 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006812 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006813 }
6814 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6815 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006816 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006817 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006818 }
6819 // We can simplify ((X << C) >>s C) into a trunc + sext.
6820 // NOTE: we could do this for any C, but that would make 'unusual' integer
6821 // types. For now, just stick to ones well-supported by the code
6822 // generators.
6823 const Type *SExtType = 0;
6824 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006825 case 1 :
6826 case 8 :
6827 case 16 :
6828 case 32 :
6829 case 64 :
6830 case 128:
6831 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6832 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006833 default: break;
6834 }
6835 if (SExtType) {
6836 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6837 InsertNewInstBefore(NewTrunc, I);
6838 return new SExtInst(NewTrunc, Ty);
6839 }
6840 // Otherwise, we can't handle it yet.
6841 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006842 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006843
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006844 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006845 if (I.getOpcode() == Instruction::Shl) {
6846 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6847 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006848 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006849 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006850 InsertNewInstBefore(Shift, I);
6851
Reid Spencer55702aa2007-03-25 21:11:44 +00006852 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6853 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006854 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006855
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006856 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006857 if (I.getOpcode() == Instruction::LShr) {
6858 assert(ShiftOp->getOpcode() == Instruction::Shl);
6859 Instruction *Shift =
6860 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6861 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006862
Reid Spencerd5e30f02007-03-26 17:18:58 +00006863 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006864 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006865 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006866
6867 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6868 } else {
6869 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006870 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006871
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006872 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006873 if (I.getOpcode() == Instruction::Shl) {
6874 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6875 ShiftOp->getOpcode() == Instruction::AShr);
6876 Instruction *Shift =
6877 BinaryOperator::create(ShiftOp->getOpcode(), X,
6878 ConstantInt::get(Ty, ShiftDiff));
6879 InsertNewInstBefore(Shift, I);
6880
Reid Spencer55702aa2007-03-25 21:11:44 +00006881 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006882 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006883 }
6884
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006885 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006886 if (I.getOpcode() == Instruction::LShr) {
6887 assert(ShiftOp->getOpcode() == Instruction::Shl);
6888 Instruction *Shift =
6889 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6890 InsertNewInstBefore(Shift, I);
6891
Reid Spencer68d27cf2007-03-26 23:45:51 +00006892 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006893 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006894 }
6895
6896 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006897 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006898 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006899 return 0;
6900}
6901
Chris Lattnera1be5662002-05-02 17:06:02 +00006902
Chris Lattnercfd65102005-10-29 04:36:15 +00006903/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6904/// expression. If so, decompose it, returning some value X, such that Val is
6905/// X*Scale+Offset.
6906///
6907static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006908 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006909 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006910 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006911 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006912 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006913 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006914 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6915 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6916 if (I->getOpcode() == Instruction::Shl) {
6917 // This is a value scaled by '1 << the shift amt'.
6918 Scale = 1U << RHS->getZExtValue();
6919 Offset = 0;
6920 return I->getOperand(0);
6921 } else if (I->getOpcode() == Instruction::Mul) {
6922 // This value is scaled by 'RHS'.
6923 Scale = RHS->getZExtValue();
6924 Offset = 0;
6925 return I->getOperand(0);
6926 } else if (I->getOpcode() == Instruction::Add) {
6927 // We have X+C. Check to see if we really have (X*C2)+C1,
6928 // where C1 is divisible by C2.
6929 unsigned SubScale;
6930 Value *SubVal =
6931 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6932 Offset += RHS->getZExtValue();
6933 Scale = SubScale;
6934 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006935 }
6936 }
6937 }
6938
6939 // Otherwise, we can't look past this.
6940 Scale = 1;
6941 Offset = 0;
6942 return Val;
6943}
6944
6945
Chris Lattnerb3f83972005-10-24 06:03:58 +00006946/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6947/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006948Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006949 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006950 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006951
Chris Lattnerb53c2382005-10-24 06:22:12 +00006952 // Remove any uses of AI that are dead.
6953 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006954
Chris Lattnerb53c2382005-10-24 06:22:12 +00006955 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6956 Instruction *User = cast<Instruction>(*UI++);
6957 if (isInstructionTriviallyDead(User)) {
6958 while (UI != E && *UI == User)
6959 ++UI; // If this instruction uses AI more than once, don't break UI.
6960
Chris Lattnerb53c2382005-10-24 06:22:12 +00006961 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006962 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006963 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006964 }
6965 }
6966
Chris Lattnerb3f83972005-10-24 06:03:58 +00006967 // Get the type really allocated and the type casted to.
6968 const Type *AllocElTy = AI.getAllocatedType();
6969 const Type *CastElTy = PTy->getElementType();
6970 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006971
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006972 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6973 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006974 if (CastElTyAlign < AllocElTyAlign) return 0;
6975
Chris Lattner39387a52005-10-24 06:35:18 +00006976 // If the allocation has multiple uses, only promote it if we are strictly
6977 // increasing the alignment of the resultant allocation. If we keep it the
6978 // same, we open the door to infinite loops of various kinds.
6979 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6980
Duncan Sands514ab342007-11-01 20:53:16 +00006981 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6982 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006983 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006984
Chris Lattner455fcc82005-10-29 03:19:53 +00006985 // See if we can satisfy the modulus by pulling a scale out of the array
6986 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006987 unsigned ArraySizeScale;
6988 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006989 Value *NumElements = // See if the array size is a decomposable linear expr.
6990 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6991
Chris Lattner455fcc82005-10-29 03:19:53 +00006992 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6993 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006994 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6995 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006996
Chris Lattner455fcc82005-10-29 03:19:53 +00006997 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6998 Value *Amt = 0;
6999 if (Scale == 1) {
7000 Amt = NumElements;
7001 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007002 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007003 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7004 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007005 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007006 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007007 else if (Scale != 1) {
7008 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
7009 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007010 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007011 }
7012
Jeff Cohen86796be2007-04-04 16:58:57 +00007013 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7014 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00007015 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
7016 Amt = InsertNewInstBefore(Tmp, AI);
7017 }
7018
Chris Lattnerb3f83972005-10-24 06:03:58 +00007019 AllocationInst *New;
7020 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007021 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007022 else
Chris Lattner6934a042007-02-11 01:23:03 +00007023 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007024 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007025 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007026
7027 // If the allocation has multiple uses, insert a cast and change all things
7028 // that used it to use the new cast. This will also hack on CI, but it will
7029 // die soon.
7030 if (!AI.hasOneUse()) {
7031 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007032 // New is the allocation instruction, pointer typed. AI is the original
7033 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7034 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007035 InsertNewInstBefore(NewCast, AI);
7036 AI.replaceAllUsesWith(NewCast);
7037 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007038 return ReplaceInstUsesWith(CI, New);
7039}
7040
Chris Lattner70074e02006-05-13 02:06:03 +00007041/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007042/// and return it as type Ty without inserting any new casts and without
7043/// changing the computed value. This is used by code that tries to decide
7044/// whether promoting or shrinking integer operations to wider or smaller types
7045/// will allow us to eliminate a truncate or extend.
7046///
7047/// This is a truncation operation if Ty is smaller than V->getType(), or an
7048/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007049bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7050 unsigned CastOpc,
7051 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007052 // We can always evaluate constants in another type.
7053 if (isa<ConstantInt>(V))
7054 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007055
7056 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007057 if (!I) return false;
7058
7059 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007060
Chris Lattner951626b2007-08-02 06:11:14 +00007061 // If this is an extension or truncate, we can often eliminate it.
7062 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7063 // If this is a cast from the destination type, we can trivially eliminate
7064 // it, and this will remove a cast overall.
7065 if (I->getOperand(0)->getType() == Ty) {
7066 // If the first operand is itself a cast, and is eliminable, do not count
7067 // this as an eliminable cast. We would prefer to eliminate those two
7068 // casts first.
7069 if (!isa<CastInst>(I->getOperand(0)))
7070 ++NumCastsRemoved;
7071 return true;
7072 }
7073 }
7074
7075 // We can't extend or shrink something that has multiple uses: doing so would
7076 // require duplicating the instruction in general, which isn't profitable.
7077 if (!I->hasOneUse()) return false;
7078
Chris Lattner70074e02006-05-13 02:06:03 +00007079 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007080 case Instruction::Add:
7081 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007082 case Instruction::And:
7083 case Instruction::Or:
7084 case Instruction::Xor:
7085 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007086 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7087 NumCastsRemoved) &&
7088 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7089 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007090
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007091 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007092 // A multiply can be truncated by truncating its operands.
7093 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7094 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7095 NumCastsRemoved) &&
7096 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7097 NumCastsRemoved);
7098
Chris Lattner46b96052006-11-29 07:18:39 +00007099 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007100 // If we are truncating the result of this SHL, and if it's a shift of a
7101 // constant amount, we can always perform a SHL in a smaller type.
7102 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007103 uint32_t BitWidth = Ty->getBitWidth();
7104 if (BitWidth < OrigTy->getBitWidth() &&
7105 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007106 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7107 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007108 }
7109 break;
7110 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007111 // If this is a truncate of a logical shr, we can truncate it to a smaller
7112 // lshr iff we know that the bits we would otherwise be shifting in are
7113 // already zeros.
7114 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007115 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7116 uint32_t BitWidth = Ty->getBitWidth();
7117 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007118 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007119 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7120 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007121 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7122 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007123 }
7124 }
Chris Lattner46b96052006-11-29 07:18:39 +00007125 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007126 case Instruction::ZExt:
7127 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007128 case Instruction::Trunc:
7129 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007130 // can safely replace it. Note that replacing it does not reduce the number
7131 // of casts in the input.
7132 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007133 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007134
Reid Spencer3da59db2006-11-27 01:05:10 +00007135 break;
7136 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007137 // TODO: Can handle more cases here.
7138 break;
7139 }
7140
7141 return false;
7142}
7143
7144/// EvaluateInDifferentType - Given an expression that
7145/// CanEvaluateInDifferentType returns true for, actually insert the code to
7146/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007147Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007148 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007149 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007150 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007151
7152 // Otherwise, it must be an instruction.
7153 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007154 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007155 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007156 case Instruction::Add:
7157 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007158 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007159 case Instruction::And:
7160 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007161 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007162 case Instruction::AShr:
7163 case Instruction::LShr:
7164 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007165 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007166 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7167 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
7168 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007169 break;
7170 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007171 case Instruction::Trunc:
7172 case Instruction::ZExt:
7173 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007174 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007175 // just return the source. There's no need to insert it because it is not
7176 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007177 if (I->getOperand(0)->getType() == Ty)
7178 return I->getOperand(0);
7179
Chris Lattner951626b2007-08-02 06:11:14 +00007180 // Otherwise, must be the same type of case, so just reinsert a new one.
7181 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7182 Ty, I->getName());
7183 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007184 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007185 // TODO: Can handle more cases here.
7186 assert(0 && "Unreachable!");
7187 break;
7188 }
7189
7190 return InsertNewInstBefore(Res, *I);
7191}
7192
Reid Spencer3da59db2006-11-27 01:05:10 +00007193/// @brief Implement the transforms common to all CastInst visitors.
7194Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007195 Value *Src = CI.getOperand(0);
7196
Dan Gohman23d9d272007-05-11 21:10:54 +00007197 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007198 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007199 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007200 if (Instruction::CastOps opc =
7201 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7202 // The first cast (CSrc) is eliminable so we need to fix up or replace
7203 // the second cast (CI). CSrc will then have a good chance of being dead.
7204 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007205 }
7206 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007207
Reid Spencer3da59db2006-11-27 01:05:10 +00007208 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007209 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7210 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7211 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007212
7213 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007214 if (isa<PHINode>(Src))
7215 if (Instruction *NV = FoldOpIntoPhi(CI))
7216 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007217
Reid Spencer3da59db2006-11-27 01:05:10 +00007218 return 0;
7219}
7220
Chris Lattnerd3e28342007-04-27 17:44:50 +00007221/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7222Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7223 Value *Src = CI.getOperand(0);
7224
Chris Lattnerd3e28342007-04-27 17:44:50 +00007225 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007226 // If casting the result of a getelementptr instruction with no offset, turn
7227 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007228 if (GEP->hasAllZeroIndices()) {
7229 // Changing the cast operand is usually not a good idea but it is safe
7230 // here because the pointer operand is being replaced with another
7231 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007232 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007233 CI.setOperand(0, GEP->getOperand(0));
7234 return &CI;
7235 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007236
7237 // If the GEP has a single use, and the base pointer is a bitcast, and the
7238 // GEP computes a constant offset, see if we can convert these three
7239 // instructions into fewer. This typically happens with unions and other
7240 // non-type-safe code.
7241 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7242 if (GEP->hasAllConstantIndices()) {
7243 // We are guaranteed to get a constant from EmitGEPOffset.
7244 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7245 int64_t Offset = OffsetV->getSExtValue();
7246
7247 // Get the base pointer input of the bitcast, and the type it points to.
7248 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7249 const Type *GEPIdxTy =
7250 cast<PointerType>(OrigBase->getType())->getElementType();
7251 if (GEPIdxTy->isSized()) {
7252 SmallVector<Value*, 8> NewIndices;
7253
Chris Lattnerc42e2262007-05-05 01:59:31 +00007254 // Start with the index over the outer type. Note that the type size
7255 // might be zero (even if the offset isn't zero) if the indexed type
7256 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007257 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007258 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007259 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007260 FirstIdx = Offset/TySize;
7261 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007262
Chris Lattnerc42e2262007-05-05 01:59:31 +00007263 // Handle silly modulus not returning values values [0..TySize).
7264 if (Offset < 0) {
7265 --FirstIdx;
7266 Offset += TySize;
7267 assert(Offset >= 0);
7268 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007269 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007270 }
7271
7272 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007273
7274 // Index into the types. If we fail, set OrigBase to null.
7275 while (Offset) {
7276 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7277 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007278 if (Offset < (int64_t)SL->getSizeInBytes()) {
7279 unsigned Elt = SL->getElementContainingOffset(Offset);
7280 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007281
Chris Lattner6b6aef82007-05-15 00:16:00 +00007282 Offset -= SL->getElementOffset(Elt);
7283 GEPIdxTy = STy->getElementType(Elt);
7284 } else {
7285 // Otherwise, we can't index into this, bail out.
7286 Offset = 0;
7287 OrigBase = 0;
7288 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007289 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7290 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007291 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007292 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7293 Offset %= EltSize;
7294 } else {
7295 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7296 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007297 GEPIdxTy = STy->getElementType();
7298 } else {
7299 // Otherwise, we can't index into this, bail out.
7300 Offset = 0;
7301 OrigBase = 0;
7302 }
7303 }
7304 if (OrigBase) {
7305 // If we were able to index down into an element, create the GEP
7306 // and bitcast the result. This eliminates one bitcast, potentially
7307 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007308 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7309 NewIndices.begin(),
7310 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007311 InsertNewInstBefore(NGEP, CI);
7312 NGEP->takeName(GEP);
7313
Chris Lattner9bc14642007-04-28 00:57:34 +00007314 if (isa<BitCastInst>(CI))
7315 return new BitCastInst(NGEP, CI.getType());
7316 assert(isa<PtrToIntInst>(CI));
7317 return new PtrToIntInst(NGEP, CI.getType());
7318 }
7319 }
7320 }
7321 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007322 }
7323
7324 return commonCastTransforms(CI);
7325}
7326
7327
7328
Chris Lattnerc739cd62007-03-03 05:27:34 +00007329/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7330/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007331/// cases.
7332/// @brief Implement the transforms common to CastInst with integer operands
7333Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7334 if (Instruction *Result = commonCastTransforms(CI))
7335 return Result;
7336
7337 Value *Src = CI.getOperand(0);
7338 const Type *SrcTy = Src->getType();
7339 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007340 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7341 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007342
Reid Spencer3da59db2006-11-27 01:05:10 +00007343 // See if we can simplify any instructions used by the LHS whose sole
7344 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007345 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7346 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007347 KnownZero, KnownOne))
7348 return &CI;
7349
7350 // If the source isn't an instruction or has more than one use then we
7351 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007352 Instruction *SrcI = dyn_cast<Instruction>(Src);
7353 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007354 return 0;
7355
Chris Lattnerc739cd62007-03-03 05:27:34 +00007356 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007357 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007358 if (!isa<BitCastInst>(CI) &&
7359 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007360 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007361 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007362 // eliminates the cast, so it is always a win. If this is a zero-extension,
7363 // we need to do an AND to maintain the clear top-part of the computation,
7364 // so we require that the input have eliminated at least one cast. If this
7365 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007366 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007367 bool DoXForm;
7368 switch (CI.getOpcode()) {
7369 default:
7370 // All the others use floating point so we shouldn't actually
7371 // get here because of the check above.
7372 assert(0 && "Unknown cast type");
7373 case Instruction::Trunc:
7374 DoXForm = true;
7375 break;
7376 case Instruction::ZExt:
7377 DoXForm = NumCastsRemoved >= 1;
7378 break;
7379 case Instruction::SExt:
7380 DoXForm = NumCastsRemoved >= 2;
7381 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007382 }
7383
7384 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007385 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7386 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007387 assert(Res->getType() == DestTy);
7388 switch (CI.getOpcode()) {
7389 default: assert(0 && "Unknown cast type!");
7390 case Instruction::Trunc:
7391 case Instruction::BitCast:
7392 // Just replace this cast with the result.
7393 return ReplaceInstUsesWith(CI, Res);
7394 case Instruction::ZExt: {
7395 // We need to emit an AND to clear the high bits.
7396 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007397 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7398 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00007399 return BinaryOperator::createAnd(Res, C);
7400 }
7401 case Instruction::SExt:
7402 // We need to emit a cast to truncate, then a cast to sext.
7403 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007404 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7405 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007406 }
7407 }
7408 }
7409
7410 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7411 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7412
7413 switch (SrcI->getOpcode()) {
7414 case Instruction::Add:
7415 case Instruction::Mul:
7416 case Instruction::And:
7417 case Instruction::Or:
7418 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007419 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007420 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7421 // Don't insert two casts if they cannot be eliminated. We allow
7422 // two casts to be inserted if the sizes are the same. This could
7423 // only be converting signedness, which is a noop.
7424 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007425 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7426 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007427 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007428 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7429 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7430 return BinaryOperator::create(
7431 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007432 }
7433 }
7434
7435 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7436 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7437 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007438 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007439 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007440 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007441 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7442 }
7443 break;
7444 case Instruction::SDiv:
7445 case Instruction::UDiv:
7446 case Instruction::SRem:
7447 case Instruction::URem:
7448 // If we are just changing the sign, rewrite.
7449 if (DestBitSize == SrcBitSize) {
7450 // Don't insert two casts if they cannot be eliminated. We allow
7451 // two casts to be inserted if the sizes are the same. This could
7452 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007453 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7454 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007455 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7456 Op0, DestTy, SrcI);
7457 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7458 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007459 return BinaryOperator::create(
7460 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7461 }
7462 }
7463 break;
7464
7465 case Instruction::Shl:
7466 // Allow changing the sign of the source operand. Do not allow
7467 // changing the size of the shift, UNLESS the shift amount is a
7468 // constant. We must not change variable sized shifts to a smaller
7469 // size, because it is undefined to shift more bits out than exist
7470 // in the value.
7471 if (DestBitSize == SrcBitSize ||
7472 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007473 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7474 Instruction::BitCast : Instruction::Trunc);
7475 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007476 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007477 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007478 }
7479 break;
7480 case Instruction::AShr:
7481 // If this is a signed shr, and if all bits shifted in are about to be
7482 // truncated off, turn it into an unsigned shr to allow greater
7483 // simplifications.
7484 if (DestBitSize < SrcBitSize &&
7485 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007486 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007487 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7488 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00007489 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007490 }
7491 }
7492 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007493 }
7494 return 0;
7495}
7496
Chris Lattner8a9f5712007-04-11 06:57:46 +00007497Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007498 if (Instruction *Result = commonIntCastTransforms(CI))
7499 return Result;
7500
7501 Value *Src = CI.getOperand(0);
7502 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007503 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7504 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007505
7506 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7507 switch (SrcI->getOpcode()) {
7508 default: break;
7509 case Instruction::LShr:
7510 // We can shrink lshr to something smaller if we know the bits shifted in
7511 // are already zeros.
7512 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007513 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007514
7515 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007516 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007517 Value* SrcIOp0 = SrcI->getOperand(0);
7518 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007519 if (ShAmt >= DestBitWidth) // All zeros.
7520 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7521
7522 // Okay, we can shrink this. Truncate the input, then return a new
7523 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007524 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7525 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7526 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007527 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007528 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007529 } else { // This is a variable shr.
7530
7531 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7532 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7533 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007534 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007535 Value *One = ConstantInt::get(SrcI->getType(), 1);
7536
Reid Spencer832254e2007-02-02 02:16:23 +00007537 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007538 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007539 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007540 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7541 SrcI->getOperand(0),
7542 "tmp"), CI);
7543 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007544 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007545 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007546 }
7547 break;
7548 }
7549 }
7550
7551 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007552}
7553
Evan Chengb98a10e2008-03-24 00:21:34 +00007554/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7555/// in order to eliminate the icmp.
7556Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7557 bool DoXform) {
7558 // If we are just checking for a icmp eq of a single bit and zext'ing it
7559 // to an integer, then shift the bit to the appropriate place and then
7560 // cast to integer to avoid the comparison.
7561 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7562 const APInt &Op1CV = Op1C->getValue();
7563
7564 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7565 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7566 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7567 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7568 if (!DoXform) return ICI;
7569
7570 Value *In = ICI->getOperand(0);
7571 Value *Sh = ConstantInt::get(In->getType(),
7572 In->getType()->getPrimitiveSizeInBits()-1);
7573 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7574 In->getName()+".lobit"),
7575 CI);
7576 if (In->getType() != CI.getType())
7577 In = CastInst::createIntegerCast(In, CI.getType(),
7578 false/*ZExt*/, "tmp", &CI);
7579
7580 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7581 Constant *One = ConstantInt::get(In->getType(), 1);
7582 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7583 In->getName()+".not"),
7584 CI);
7585 }
7586
7587 return ReplaceInstUsesWith(CI, In);
7588 }
7589
7590
7591
7592 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7593 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7594 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7595 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7596 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7597 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7598 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7599 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7600 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7601 // This only works for EQ and NE
7602 ICI->isEquality()) {
7603 // If Op1C some other power of two, convert:
7604 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7605 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7606 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7607 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7608
7609 APInt KnownZeroMask(~KnownZero);
7610 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7611 if (!DoXform) return ICI;
7612
7613 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7614 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7615 // (X&4) == 2 --> false
7616 // (X&4) != 2 --> true
7617 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7618 Res = ConstantExpr::getZExt(Res, CI.getType());
7619 return ReplaceInstUsesWith(CI, Res);
7620 }
7621
7622 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7623 Value *In = ICI->getOperand(0);
7624 if (ShiftAmt) {
7625 // Perform a logical shr by shiftamt.
7626 // Insert the shift to put the result in the low bit.
7627 In = InsertNewInstBefore(BinaryOperator::createLShr(In,
7628 ConstantInt::get(In->getType(), ShiftAmt),
7629 In->getName()+".lobit"), CI);
7630 }
7631
7632 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7633 Constant *One = ConstantInt::get(In->getType(), 1);
7634 In = BinaryOperator::createXor(In, One, "tmp");
7635 InsertNewInstBefore(cast<Instruction>(In), CI);
7636 }
7637
7638 if (CI.getType() == In->getType())
7639 return ReplaceInstUsesWith(CI, In);
7640 else
7641 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7642 }
7643 }
7644 }
7645
7646 return 0;
7647}
7648
Chris Lattner8a9f5712007-04-11 06:57:46 +00007649Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007650 // If one of the common conversion will work ..
7651 if (Instruction *Result = commonIntCastTransforms(CI))
7652 return Result;
7653
7654 Value *Src = CI.getOperand(0);
7655
7656 // If this is a cast of a cast
7657 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007658 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7659 // types and if the sizes are just right we can convert this into a logical
7660 // 'and' which will be much cheaper than the pair of casts.
7661 if (isa<TruncInst>(CSrc)) {
7662 // Get the sizes of the types involved
7663 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007664 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7665 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7666 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007667 // If we're actually extending zero bits and the trunc is a no-op
7668 if (MidSize < DstSize && SrcSize == DstSize) {
7669 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007670 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007671 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007672 Instruction *And =
7673 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7674 // Unfortunately, if the type changed, we need to cast it back.
7675 if (And->getType() != CI.getType()) {
7676 And->setName(CSrc->getName()+".mask");
7677 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007678 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007679 }
7680 return And;
7681 }
7682 }
7683 }
7684
Evan Chengb98a10e2008-03-24 00:21:34 +00007685 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7686 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007687
Evan Chengb98a10e2008-03-24 00:21:34 +00007688 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7689 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7690 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7691 // of the (zext icmp) will be transformed.
7692 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7693 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7694 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7695 (transformZExtICmp(LHS, CI, false) ||
7696 transformZExtICmp(RHS, CI, false))) {
7697 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7698 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7699 return BinaryOperator::create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007700 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007701 }
7702
Reid Spencer3da59db2006-11-27 01:05:10 +00007703 return 0;
7704}
7705
Chris Lattner8a9f5712007-04-11 06:57:46 +00007706Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007707 if (Instruction *I = commonIntCastTransforms(CI))
7708 return I;
7709
Chris Lattner8a9f5712007-04-11 06:57:46 +00007710 Value *Src = CI.getOperand(0);
7711
7712 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7713 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7714 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7715 // If we are just checking for a icmp eq of a single bit and zext'ing it
7716 // to an integer, then shift the bit to the appropriate place and then
7717 // cast to integer to avoid the comparison.
7718 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7719 const APInt &Op1CV = Op1C->getValue();
7720
7721 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7722 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7723 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7724 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7725 Value *In = ICI->getOperand(0);
7726 Value *Sh = ConstantInt::get(In->getType(),
7727 In->getType()->getPrimitiveSizeInBits()-1);
7728 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007729 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007730 CI);
7731 if (In->getType() != CI.getType())
7732 In = CastInst::createIntegerCast(In, CI.getType(),
7733 true/*SExt*/, "tmp", &CI);
7734
7735 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7736 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7737 In->getName()+".not"), CI);
7738
7739 return ReplaceInstUsesWith(CI, In);
7740 }
7741 }
7742 }
7743
Chris Lattnerba417832007-04-11 06:12:58 +00007744 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007745}
7746
Chris Lattnerb7530652008-01-27 05:29:54 +00007747/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7748/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007749static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007750 APFloat F = CFP->getValueAPF();
7751 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007752 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007753 return 0;
7754}
7755
7756/// LookThroughFPExtensions - If this is an fp extension instruction, look
7757/// through it until we get the source value.
7758static Value *LookThroughFPExtensions(Value *V) {
7759 if (Instruction *I = dyn_cast<Instruction>(V))
7760 if (I->getOpcode() == Instruction::FPExt)
7761 return LookThroughFPExtensions(I->getOperand(0));
7762
7763 // If this value is a constant, return the constant in the smallest FP type
7764 // that can accurately represent it. This allows us to turn
7765 // (float)((double)X+2.0) into x+2.0f.
7766 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7767 if (CFP->getType() == Type::PPC_FP128Ty)
7768 return V; // No constant folding of this.
7769 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007770 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007771 return V;
7772 if (CFP->getType() == Type::DoubleTy)
7773 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007774 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007775 return V;
7776 // Don't try to shrink to various long double types.
7777 }
7778
7779 return V;
7780}
7781
7782Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7783 if (Instruction *I = commonCastTransforms(CI))
7784 return I;
7785
7786 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7787 // smaller than the destination type, we can eliminate the truncate by doing
7788 // the add as the smaller type. This applies to add/sub/mul/div as well as
7789 // many builtins (sqrt, etc).
7790 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7791 if (OpI && OpI->hasOneUse()) {
7792 switch (OpI->getOpcode()) {
7793 default: break;
7794 case Instruction::Add:
7795 case Instruction::Sub:
7796 case Instruction::Mul:
7797 case Instruction::FDiv:
7798 case Instruction::FRem:
7799 const Type *SrcTy = OpI->getType();
7800 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7801 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7802 if (LHSTrunc->getType() != SrcTy &&
7803 RHSTrunc->getType() != SrcTy) {
7804 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7805 // If the source types were both smaller than the destination type of
7806 // the cast, do this xform.
7807 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7808 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7809 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7810 CI.getType(), CI);
7811 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7812 CI.getType(), CI);
7813 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7814 }
7815 }
7816 break;
7817 }
7818 }
7819 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007820}
7821
7822Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7823 return commonCastTransforms(CI);
7824}
7825
7826Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007827 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007828}
7829
7830Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007831 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007832}
7833
7834Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7835 return commonCastTransforms(CI);
7836}
7837
7838Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7839 return commonCastTransforms(CI);
7840}
7841
7842Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007843 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007844}
7845
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007846Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7847 if (Instruction *I = commonCastTransforms(CI))
7848 return I;
7849
7850 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7851 if (!DestPointee->isSized()) return 0;
7852
7853 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7854 ConstantInt *Cst;
7855 Value *X;
7856 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7857 m_ConstantInt(Cst)))) {
7858 // If the source and destination operands have the same type, see if this
7859 // is a single-index GEP.
7860 if (X->getType() == CI.getType()) {
7861 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007862 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007863
7864 // Convert the constant to intptr type.
7865 APInt Offset = Cst->getValue();
7866 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7867
7868 // If Offset is evenly divisible by Size, we can do this xform.
7869 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7870 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007871 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007872 }
7873 }
7874 // TODO: Could handle other cases, e.g. where add is indexing into field of
7875 // struct etc.
7876 } else if (CI.getOperand(0)->hasOneUse() &&
7877 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7878 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7879 // "inttoptr+GEP" instead of "add+intptr".
7880
7881 // Get the size of the pointee type.
7882 uint64_t Size = TD->getABITypeSize(DestPointee);
7883
7884 // Convert the constant to intptr type.
7885 APInt Offset = Cst->getValue();
7886 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7887
7888 // If Offset is evenly divisible by Size, we can do this xform.
7889 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7890 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7891
7892 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7893 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007894 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007895 }
7896 }
7897 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007898}
7899
Chris Lattnerd3e28342007-04-27 17:44:50 +00007900Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007901 // If the operands are integer typed then apply the integer transforms,
7902 // otherwise just apply the common ones.
7903 Value *Src = CI.getOperand(0);
7904 const Type *SrcTy = Src->getType();
7905 const Type *DestTy = CI.getType();
7906
Chris Lattner42a75512007-01-15 02:27:26 +00007907 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007908 if (Instruction *Result = commonIntCastTransforms(CI))
7909 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007910 } else if (isa<PointerType>(SrcTy)) {
7911 if (Instruction *I = commonPointerCastTransforms(CI))
7912 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007913 } else {
7914 if (Instruction *Result = commonCastTransforms(CI))
7915 return Result;
7916 }
7917
7918
7919 // Get rid of casts from one type to the same type. These are useless and can
7920 // be replaced by the operand.
7921 if (DestTy == Src->getType())
7922 return ReplaceInstUsesWith(CI, Src);
7923
Reid Spencer3da59db2006-11-27 01:05:10 +00007924 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007925 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7926 const Type *DstElTy = DstPTy->getElementType();
7927 const Type *SrcElTy = SrcPTy->getElementType();
7928
Nate Begeman83ad90a2008-03-31 00:22:16 +00007929 // If the address spaces don't match, don't eliminate the bitcast, which is
7930 // required for changing types.
7931 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7932 return 0;
7933
Chris Lattnerd3e28342007-04-27 17:44:50 +00007934 // If we are casting a malloc or alloca to a pointer to a type of the same
7935 // size, rewrite the allocation instruction to allocate the "right" type.
7936 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7937 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7938 return V;
7939
Chris Lattnerd717c182007-05-05 22:32:24 +00007940 // If the source and destination are pointers, and this cast is equivalent
7941 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007942 // This can enhance SROA and other transforms that want type-safe pointers.
7943 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7944 unsigned NumZeros = 0;
7945 while (SrcElTy != DstElTy &&
7946 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7947 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7948 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7949 ++NumZeros;
7950 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007951
Chris Lattnerd3e28342007-04-27 17:44:50 +00007952 // If we found a path from the src to dest, create the getelementptr now.
7953 if (SrcElTy == DstElTy) {
7954 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007955 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7956 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007957 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007958 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007959
Reid Spencer3da59db2006-11-27 01:05:10 +00007960 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7961 if (SVI->hasOneUse()) {
7962 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7963 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007964 if (isa<VectorType>(DestTy) &&
7965 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007966 SVI->getType()->getNumElements()) {
7967 CastInst *Tmp;
7968 // If either of the operands is a cast from CI.getType(), then
7969 // evaluating the shuffle in the casted destination's type will allow
7970 // us to eliminate at least one cast.
7971 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7972 Tmp->getOperand(0)->getType() == DestTy) ||
7973 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7974 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007975 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7976 SVI->getOperand(0), DestTy, &CI);
7977 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7978 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007979 // Return a new shuffle vector. Use the same element ID's, as we
7980 // know the vector types match #elts.
7981 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007982 }
7983 }
7984 }
7985 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007986 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007987}
7988
Chris Lattnere576b912004-04-09 23:46:01 +00007989/// GetSelectFoldableOperands - We want to turn code that looks like this:
7990/// %C = or %A, %B
7991/// %D = select %cond, %C, %A
7992/// into:
7993/// %C = select %cond, %B, 0
7994/// %D = or %A, %C
7995///
7996/// Assuming that the specified instruction is an operand to the select, return
7997/// a bitmask indicating which operands of this instruction are foldable if they
7998/// equal the other incoming value of the select.
7999///
8000static unsigned GetSelectFoldableOperands(Instruction *I) {
8001 switch (I->getOpcode()) {
8002 case Instruction::Add:
8003 case Instruction::Mul:
8004 case Instruction::And:
8005 case Instruction::Or:
8006 case Instruction::Xor:
8007 return 3; // Can fold through either operand.
8008 case Instruction::Sub: // Can only fold on the amount subtracted.
8009 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008010 case Instruction::LShr:
8011 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008012 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008013 default:
8014 return 0; // Cannot fold
8015 }
8016}
8017
8018/// GetSelectFoldableConstant - For the same transformation as the previous
8019/// function, return the identity constant that goes into the select.
8020static Constant *GetSelectFoldableConstant(Instruction *I) {
8021 switch (I->getOpcode()) {
8022 default: assert(0 && "This cannot happen!"); abort();
8023 case Instruction::Add:
8024 case Instruction::Sub:
8025 case Instruction::Or:
8026 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008027 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008028 case Instruction::LShr:
8029 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008030 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008031 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008032 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008033 case Instruction::Mul:
8034 return ConstantInt::get(I->getType(), 1);
8035 }
8036}
8037
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008038/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8039/// have the same opcode and only one use each. Try to simplify this.
8040Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8041 Instruction *FI) {
8042 if (TI->getNumOperands() == 1) {
8043 // If this is a non-volatile load or a cast from the same type,
8044 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008045 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008046 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8047 return 0;
8048 } else {
8049 return 0; // unknown unary op.
8050 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008051
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008052 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008053 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8054 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008055 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008056 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
8057 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008058 }
8059
Reid Spencer832254e2007-02-02 02:16:23 +00008060 // Only handle binary operators here.
8061 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008062 return 0;
8063
8064 // Figure out if the operations have any operands in common.
8065 Value *MatchOp, *OtherOpT, *OtherOpF;
8066 bool MatchIsOpZero;
8067 if (TI->getOperand(0) == FI->getOperand(0)) {
8068 MatchOp = TI->getOperand(0);
8069 OtherOpT = TI->getOperand(1);
8070 OtherOpF = FI->getOperand(1);
8071 MatchIsOpZero = true;
8072 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8073 MatchOp = TI->getOperand(1);
8074 OtherOpT = TI->getOperand(0);
8075 OtherOpF = FI->getOperand(0);
8076 MatchIsOpZero = false;
8077 } else if (!TI->isCommutative()) {
8078 return 0;
8079 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8080 MatchOp = TI->getOperand(0);
8081 OtherOpT = TI->getOperand(1);
8082 OtherOpF = FI->getOperand(0);
8083 MatchIsOpZero = true;
8084 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8085 MatchOp = TI->getOperand(1);
8086 OtherOpT = TI->getOperand(0);
8087 OtherOpF = FI->getOperand(1);
8088 MatchIsOpZero = true;
8089 } else {
8090 return 0;
8091 }
8092
8093 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008094 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8095 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008096 InsertNewInstBefore(NewSI, SI);
8097
8098 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8099 if (MatchIsOpZero)
8100 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
8101 else
8102 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008103 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008104 assert(0 && "Shouldn't get here");
8105 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008106}
8107
Chris Lattner3d69f462004-03-12 05:52:32 +00008108Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008109 Value *CondVal = SI.getCondition();
8110 Value *TrueVal = SI.getTrueValue();
8111 Value *FalseVal = SI.getFalseValue();
8112
8113 // select true, X, Y -> X
8114 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008115 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008116 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008117
8118 // select C, X, X -> X
8119 if (TrueVal == FalseVal)
8120 return ReplaceInstUsesWith(SI, TrueVal);
8121
Chris Lattnere87597f2004-10-16 18:11:37 +00008122 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8123 return ReplaceInstUsesWith(SI, FalseVal);
8124 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8125 return ReplaceInstUsesWith(SI, TrueVal);
8126 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8127 if (isa<Constant>(TrueVal))
8128 return ReplaceInstUsesWith(SI, TrueVal);
8129 else
8130 return ReplaceInstUsesWith(SI, FalseVal);
8131 }
8132
Reid Spencer4fe16d62007-01-11 18:21:29 +00008133 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008134 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008135 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008136 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00008137 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008138 } else {
8139 // Change: A = select B, false, C --> A = and !B, C
8140 Value *NotCond =
8141 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
8142 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00008143 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008144 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008145 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008146 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008147 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00008148 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008149 } else {
8150 // Change: A = select B, C, true --> A = or !B, C
8151 Value *NotCond =
8152 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
8153 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00008154 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008155 }
8156 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008157
8158 // select a, b, a -> a&b
8159 // select a, a, b -> a|b
8160 if (CondVal == TrueVal)
8161 return BinaryOperator::createOr(CondVal, FalseVal);
8162 else if (CondVal == FalseVal)
8163 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008164 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008165
Chris Lattner2eefe512004-04-09 19:05:30 +00008166 // Selecting between two integer constants?
8167 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8168 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008169 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008170 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008171 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008172 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008173 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008174 Value *NotCond =
8175 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008176 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008177 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008178 }
Chris Lattnerba417832007-04-11 06:12:58 +00008179
8180 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008181
Reid Spencere4d87aa2006-12-23 06:05:41 +00008182 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008183
Reid Spencere4d87aa2006-12-23 06:05:41 +00008184 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008185 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008186 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008187 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008188 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008189 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008190 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008191 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008192 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8193 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
8194 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008195 InsertNewInstBefore(SRA, SI);
8196
Reid Spencer3da59db2006-11-27 01:05:10 +00008197 // Finally, convert to the type of the select RHS. We figure out
8198 // if this requires a SExt, Trunc or BitCast based on the sizes.
8199 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008200 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8201 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008202 if (SRASize < SISize)
8203 opc = Instruction::SExt;
8204 else if (SRASize > SISize)
8205 opc = Instruction::Trunc;
8206 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008207 }
8208 }
8209
8210
8211 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008212 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008213 // non-constant value, eliminate this whole mess. This corresponds to
8214 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008215 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008216 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008217 cast<Constant>(IC->getOperand(1))->isNullValue())
8218 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8219 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008220 isa<ConstantInt>(ICA->getOperand(1)) &&
8221 (ICA->getOperand(1) == TrueValC ||
8222 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008223 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8224 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008225 // know whether we have a icmp_ne or icmp_eq and whether the
8226 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008227 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008228 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008229 Value *V = ICA;
8230 if (ShouldNotVal)
8231 V = InsertNewInstBefore(BinaryOperator::create(
8232 Instruction::Xor, V, ICA->getOperand(1)), SI);
8233 return ReplaceInstUsesWith(SI, V);
8234 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008235 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008236 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008237
8238 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008239 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8240 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008241 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008242 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8243 // This is not safe in general for floating point:
8244 // consider X== -0, Y== +0.
8245 // It becomes safe if either operand is a nonzero constant.
8246 ConstantFP *CFPt, *CFPf;
8247 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8248 !CFPt->getValueAPF().isZero()) ||
8249 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8250 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008251 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008252 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008253 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008254 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008255 return ReplaceInstUsesWith(SI, TrueVal);
8256 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8257
Reid Spencere4d87aa2006-12-23 06:05:41 +00008258 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008259 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008260 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8261 // This is not safe in general for floating point:
8262 // consider X== -0, Y== +0.
8263 // It becomes safe if either operand is a nonzero constant.
8264 ConstantFP *CFPt, *CFPf;
8265 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8266 !CFPt->getValueAPF().isZero()) ||
8267 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8268 !CFPf->getValueAPF().isZero()))
8269 return ReplaceInstUsesWith(SI, FalseVal);
8270 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008271 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008272 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8273 return ReplaceInstUsesWith(SI, TrueVal);
8274 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8275 }
8276 }
8277
8278 // See if we are selecting two values based on a comparison of the two values.
8279 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8280 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8281 // Transform (X == Y) ? X : Y -> Y
8282 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8283 return ReplaceInstUsesWith(SI, FalseVal);
8284 // Transform (X != Y) ? X : Y -> X
8285 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8286 return ReplaceInstUsesWith(SI, TrueVal);
8287 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8288
8289 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8290 // Transform (X == Y) ? Y : X -> X
8291 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8292 return ReplaceInstUsesWith(SI, FalseVal);
8293 // Transform (X != Y) ? Y : X -> Y
8294 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008295 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008296 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8297 }
8298 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008299
Chris Lattner87875da2005-01-13 22:52:24 +00008300 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8301 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8302 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008303 Instruction *AddOp = 0, *SubOp = 0;
8304
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008305 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8306 if (TI->getOpcode() == FI->getOpcode())
8307 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8308 return IV;
8309
8310 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8311 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008312 if (TI->getOpcode() == Instruction::Sub &&
8313 FI->getOpcode() == Instruction::Add) {
8314 AddOp = FI; SubOp = TI;
8315 } else if (FI->getOpcode() == Instruction::Sub &&
8316 TI->getOpcode() == Instruction::Add) {
8317 AddOp = TI; SubOp = FI;
8318 }
8319
8320 if (AddOp) {
8321 Value *OtherAddOp = 0;
8322 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8323 OtherAddOp = AddOp->getOperand(1);
8324 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8325 OtherAddOp = AddOp->getOperand(0);
8326 }
8327
8328 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008329 // So at this point we know we have (Y -> OtherAddOp):
8330 // select C, (add X, Y), (sub X, Z)
8331 Value *NegVal; // Compute -Z
8332 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8333 NegVal = ConstantExpr::getNeg(C);
8334 } else {
8335 NegVal = InsertNewInstBefore(
8336 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008337 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008338
8339 Value *NewTrueOp = OtherAddOp;
8340 Value *NewFalseOp = NegVal;
8341 if (AddOp != TI)
8342 std::swap(NewTrueOp, NewFalseOp);
8343 Instruction *NewSel =
Gabor Greif051a9502008-04-06 20:25:17 +00008344 SelectInst::Create(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008345
8346 NewSel = InsertNewInstBefore(NewSel, SI);
8347 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008348 }
8349 }
8350 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008351
Chris Lattnere576b912004-04-09 23:46:01 +00008352 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008353 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008354 // See the comment above GetSelectFoldableOperands for a description of the
8355 // transformation we are doing here.
8356 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8357 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8358 !isa<Constant>(FalseVal))
8359 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8360 unsigned OpToFold = 0;
8361 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8362 OpToFold = 1;
8363 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8364 OpToFold = 2;
8365 }
8366
8367 if (OpToFold) {
8368 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008369 Instruction *NewSel =
Gabor Greif051a9502008-04-06 20:25:17 +00008370 SelectInst::Create(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008371 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008372 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008373 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8374 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008375 else {
8376 assert(0 && "Unknown instruction!!");
8377 }
8378 }
8379 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008380
Chris Lattnere576b912004-04-09 23:46:01 +00008381 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8382 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8383 !isa<Constant>(TrueVal))
8384 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8385 unsigned OpToFold = 0;
8386 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8387 OpToFold = 1;
8388 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8389 OpToFold = 2;
8390 }
8391
8392 if (OpToFold) {
8393 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008394 Instruction *NewSel =
Gabor Greif051a9502008-04-06 20:25:17 +00008395 SelectInst::Create(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008396 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008397 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008398 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8399 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008400 else
Chris Lattnere576b912004-04-09 23:46:01 +00008401 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008402 }
8403 }
8404 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008405
8406 if (BinaryOperator::isNot(CondVal)) {
8407 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8408 SI.setOperand(1, FalseVal);
8409 SI.setOperand(2, TrueVal);
8410 return &SI;
8411 }
8412
Chris Lattner3d69f462004-03-12 05:52:32 +00008413 return 0;
8414}
8415
Dan Gohmaneee962e2008-04-10 18:43:06 +00008416/// EnforceKnownAlignment - If the specified pointer points to an object that
8417/// we control, modify the object's alignment to PrefAlign. This isn't
8418/// often possible though. If alignment is important, a more reliable approach
8419/// is to simply align all global variables and allocation instructions to
8420/// their preferred alignment from the beginning.
8421///
8422static unsigned EnforceKnownAlignment(Value *V,
8423 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008424
Dan Gohmaneee962e2008-04-10 18:43:06 +00008425 User *U = dyn_cast<User>(V);
8426 if (!U) return Align;
8427
8428 switch (getOpcode(U)) {
8429 default: break;
8430 case Instruction::BitCast:
8431 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8432 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008433 // If all indexes are zero, it is just the alignment of the base pointer.
8434 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008435 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8436 if (!isa<Constant>(U->getOperand(i)) ||
8437 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008438 AllZeroOperands = false;
8439 break;
8440 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008441
8442 if (AllZeroOperands) {
8443 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008444 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008445 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008446 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008447 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008448 }
8449
8450 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8451 // If there is a large requested alignment and we can, bump up the alignment
8452 // of the global.
8453 if (!GV->isDeclaration()) {
8454 GV->setAlignment(PrefAlign);
8455 Align = PrefAlign;
8456 }
8457 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8458 // If there is a requested alignment and if this is an alloca, round up. We
8459 // don't do this for malloc, because some systems can't respect the request.
8460 if (isa<AllocaInst>(AI)) {
8461 AI->setAlignment(PrefAlign);
8462 Align = PrefAlign;
8463 }
8464 }
8465
8466 return Align;
8467}
8468
8469/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8470/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8471/// and it is more than the alignment of the ultimate object, see if we can
8472/// increase the alignment of the ultimate object, making this check succeed.
8473unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8474 unsigned PrefAlign) {
8475 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8476 sizeof(PrefAlign) * CHAR_BIT;
8477 APInt Mask = APInt::getAllOnesValue(BitWidth);
8478 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8479 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8480 unsigned TrailZ = KnownZero.countTrailingOnes();
8481 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8482
8483 if (PrefAlign > Align)
8484 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8485
8486 // We don't need to make any adjustment.
8487 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008488}
8489
Chris Lattnerf497b022008-01-13 23:50:23 +00008490Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008491 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8492 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008493 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8494 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8495
8496 if (CopyAlign < MinAlign) {
8497 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8498 return MI;
8499 }
8500
8501 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8502 // load/store.
8503 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8504 if (MemOpLength == 0) return 0;
8505
Chris Lattner37ac6082008-01-14 00:28:35 +00008506 // Source and destination pointer types are always "i8*" for intrinsic. See
8507 // if the size is something we can handle with a single primitive load/store.
8508 // A single load+store correctly handles overlapping memory in the memmove
8509 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008510 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008511 if (Size == 0) return MI; // Delete this mem transfer.
8512
8513 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008514 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008515
Chris Lattner37ac6082008-01-14 00:28:35 +00008516 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008517 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008518
8519 // Memcpy forces the use of i8* for the source and destination. That means
8520 // that if you're using memcpy to move one double around, you'll get a cast
8521 // from double* to i8*. We'd much rather use a double load+store rather than
8522 // an i64 load+store, here because this improves the odds that the source or
8523 // dest address will be promotable. See if we can find a better type than the
8524 // integer datatype.
8525 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8526 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8527 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8528 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8529 // down through these levels if so.
8530 while (!SrcETy->isFirstClassType()) {
8531 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8532 if (STy->getNumElements() == 1)
8533 SrcETy = STy->getElementType(0);
8534 else
8535 break;
8536 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8537 if (ATy->getNumElements() == 1)
8538 SrcETy = ATy->getElementType();
8539 else
8540 break;
8541 } else
8542 break;
8543 }
8544
8545 if (SrcETy->isFirstClassType())
8546 NewPtrTy = PointerType::getUnqual(SrcETy);
8547 }
8548 }
8549
8550
Chris Lattnerf497b022008-01-13 23:50:23 +00008551 // If the memcpy/memmove provides better alignment info than we can
8552 // infer, use it.
8553 SrcAlign = std::max(SrcAlign, CopyAlign);
8554 DstAlign = std::max(DstAlign, CopyAlign);
8555
8556 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8557 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008558 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8559 InsertNewInstBefore(L, *MI);
8560 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8561
8562 // Set the size of the copy to 0, it will be deleted on the next iteration.
8563 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8564 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008565}
Chris Lattner3d69f462004-03-12 05:52:32 +00008566
Chris Lattner69ea9d22008-04-30 06:39:11 +00008567Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8568 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8569 if (MI->getAlignment()->getZExtValue() < Alignment) {
8570 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8571 return MI;
8572 }
8573
8574 // Extract the length and alignment and fill if they are constant.
8575 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8576 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8577 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8578 return 0;
8579 uint64_t Len = LenC->getZExtValue();
8580 Alignment = MI->getAlignment()->getZExtValue();
8581
8582 // If the length is zero, this is a no-op
8583 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8584
8585 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8586 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8587 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8588
8589 Value *Dest = MI->getDest();
8590 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8591
8592 // Alignment 0 is identity for alignment 1 for memset, but not store.
8593 if (Alignment == 0) Alignment = 1;
8594
8595 // Extract the fill value and store.
8596 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8597 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8598 Alignment), *MI);
8599
8600 // Set the size of the copy to 0, it will be deleted on the next iteration.
8601 MI->setLength(Constant::getNullValue(LenC->getType()));
8602 return MI;
8603 }
8604
8605 return 0;
8606}
8607
8608
Chris Lattner8b0ea312006-01-13 20:11:04 +00008609/// visitCallInst - CallInst simplification. This mostly only handles folding
8610/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8611/// the heavy lifting.
8612///
Chris Lattner9fe38862003-06-19 17:00:31 +00008613Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008614 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8615 if (!II) return visitCallSite(&CI);
8616
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008617 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8618 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008619 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008620 bool Changed = false;
8621
8622 // memmove/cpy/set of zero bytes is a noop.
8623 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8624 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8625
Chris Lattner35b9e482004-10-12 04:52:52 +00008626 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008627 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008628 // Replace the instruction with just byte operations. We would
8629 // transform other cases to loads/stores, but we don't know if
8630 // alignment is sufficient.
8631 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008632 }
8633
Chris Lattner35b9e482004-10-12 04:52:52 +00008634 // If we have a memmove and the source operation is a constant global,
8635 // then the source and dest pointers can't alias, so we can change this
8636 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008637 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008638 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8639 if (GVSrc->isConstant()) {
8640 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008641 Intrinsic::ID MemCpyID;
8642 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8643 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008644 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008645 MemCpyID = Intrinsic::memcpy_i64;
8646 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008647 Changed = true;
8648 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008649 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008650
Chris Lattner95a959d2006-03-06 20:18:44 +00008651 // If we can determine a pointer alignment that is bigger than currently
8652 // set, update the alignment.
8653 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008654 if (Instruction *I = SimplifyMemTransfer(MI))
8655 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008656 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8657 if (Instruction *I = SimplifyMemSet(MSI))
8658 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008659 }
8660
Chris Lattner8b0ea312006-01-13 20:11:04 +00008661 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008662 } else {
8663 switch (II->getIntrinsicID()) {
8664 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008665 case Intrinsic::ppc_altivec_lvx:
8666 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008667 case Intrinsic::x86_sse_loadu_ps:
8668 case Intrinsic::x86_sse2_loadu_pd:
8669 case Intrinsic::x86_sse2_loadu_dq:
8670 // Turn PPC lvx -> load if the pointer is known aligned.
8671 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008672 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008673 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8674 PointerType::getUnqual(II->getType()),
8675 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008676 return new LoadInst(Ptr);
8677 }
8678 break;
8679 case Intrinsic::ppc_altivec_stvx:
8680 case Intrinsic::ppc_altivec_stvxl:
8681 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008682 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008683 const Type *OpPtrTy =
8684 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008685 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008686 return new StoreInst(II->getOperand(1), Ptr);
8687 }
8688 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008689 case Intrinsic::x86_sse_storeu_ps:
8690 case Intrinsic::x86_sse2_storeu_pd:
8691 case Intrinsic::x86_sse2_storeu_dq:
8692 case Intrinsic::x86_sse2_storel_dq:
8693 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008694 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008695 const Type *OpPtrTy =
8696 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008697 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008698 return new StoreInst(II->getOperand(2), Ptr);
8699 }
8700 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008701
8702 case Intrinsic::x86_sse_cvttss2si: {
8703 // These intrinsics only demands the 0th element of its input vector. If
8704 // we can simplify the input based on that, do so now.
8705 uint64_t UndefElts;
8706 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8707 UndefElts)) {
8708 II->setOperand(1, V);
8709 return II;
8710 }
8711 break;
8712 }
8713
Chris Lattnere2ed0572006-04-06 19:19:17 +00008714 case Intrinsic::ppc_altivec_vperm:
8715 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008716 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008717 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8718
8719 // Check that all of the elements are integer constants or undefs.
8720 bool AllEltsOk = true;
8721 for (unsigned i = 0; i != 16; ++i) {
8722 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8723 !isa<UndefValue>(Mask->getOperand(i))) {
8724 AllEltsOk = false;
8725 break;
8726 }
8727 }
8728
8729 if (AllEltsOk) {
8730 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008731 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8732 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008733 Value *Result = UndefValue::get(Op0->getType());
8734
8735 // Only extract each element once.
8736 Value *ExtractedElts[32];
8737 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8738
8739 for (unsigned i = 0; i != 16; ++i) {
8740 if (isa<UndefValue>(Mask->getOperand(i)))
8741 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008742 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008743 Idx &= 31; // Match the hardware behavior.
8744
8745 if (ExtractedElts[Idx] == 0) {
8746 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008747 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008748 InsertNewInstBefore(Elt, CI);
8749 ExtractedElts[Idx] = Elt;
8750 }
8751
8752 // Insert this value into the result vector.
Gabor Greif051a9502008-04-06 20:25:17 +00008753 Result = InsertElementInst::Create(Result, ExtractedElts[Idx], i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008754 InsertNewInstBefore(cast<Instruction>(Result), CI);
8755 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008756 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008757 }
8758 }
8759 break;
8760
Chris Lattnera728ddc2006-01-13 21:28:09 +00008761 case Intrinsic::stackrestore: {
8762 // If the save is right next to the restore, remove the restore. This can
8763 // happen when variable allocas are DCE'd.
8764 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8765 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8766 BasicBlock::iterator BI = SS;
8767 if (&*++BI == II)
8768 return EraseInstFromFunction(CI);
8769 }
8770 }
8771
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008772 // Scan down this block to see if there is another stack restore in the
8773 // same block without an intervening call/alloca.
8774 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008775 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008776 bool CannotRemove = false;
8777 for (++BI; &*BI != TI; ++BI) {
8778 if (isa<AllocaInst>(BI)) {
8779 CannotRemove = true;
8780 break;
8781 }
8782 if (isa<CallInst>(BI)) {
8783 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008784 CannotRemove = true;
8785 break;
8786 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008787 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008788 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008789 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008790 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008791
8792 // If the stack restore is in a return/unwind block and if there are no
8793 // allocas or calls between the restore and the return, nuke the restore.
8794 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8795 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008796 break;
8797 }
8798 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008799 }
8800
Chris Lattner8b0ea312006-01-13 20:11:04 +00008801 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008802}
8803
8804// InvokeInst simplification
8805//
8806Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008807 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008808}
8809
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008810/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8811/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008812static bool isSafeToEliminateVarargsCast(const CallSite CS,
8813 const CastInst * const CI,
8814 const TargetData * const TD,
8815 const int ix) {
8816 if (!CI->isLosslessCast())
8817 return false;
8818
8819 // The size of ByVal arguments is derived from the type, so we
8820 // can't change to a type with a different size. If the size were
8821 // passed explicitly we could avoid this check.
8822 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8823 return true;
8824
8825 const Type* SrcTy =
8826 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8827 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8828 if (!SrcTy->isSized() || !DstTy->isSized())
8829 return false;
8830 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8831 return false;
8832 return true;
8833}
8834
Chris Lattnera44d8a22003-10-07 22:32:43 +00008835// visitCallSite - Improvements for call and invoke instructions.
8836//
8837Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008838 bool Changed = false;
8839
8840 // If the callee is a constexpr cast of a function, attempt to move the cast
8841 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008842 if (transformConstExprCastCall(CS)) return 0;
8843
Chris Lattner6c266db2003-10-07 22:54:13 +00008844 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008845
Chris Lattner08b22ec2005-05-13 07:09:09 +00008846 if (Function *CalleeF = dyn_cast<Function>(Callee))
8847 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8848 Instruction *OldCall = CS.getInstruction();
8849 // If the call and callee calling conventions don't match, this call must
8850 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008851 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008852 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8853 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008854 if (!OldCall->use_empty())
8855 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8856 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8857 return EraseInstFromFunction(*OldCall);
8858 return 0;
8859 }
8860
Chris Lattner17be6352004-10-18 02:59:09 +00008861 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8862 // This instruction is not reachable, just remove it. We insert a store to
8863 // undef so that we know that this code is not reachable, despite the fact
8864 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008865 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008866 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008867 CS.getInstruction());
8868
8869 if (!CS.getInstruction()->use_empty())
8870 CS.getInstruction()->
8871 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8872
8873 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8874 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008875 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8876 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008877 }
Chris Lattner17be6352004-10-18 02:59:09 +00008878 return EraseInstFromFunction(*CS.getInstruction());
8879 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008880
Duncan Sandscdb6d922007-09-17 10:26:40 +00008881 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8882 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8883 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8884 return transformCallThroughTrampoline(CS);
8885
Chris Lattner6c266db2003-10-07 22:54:13 +00008886 const PointerType *PTy = cast<PointerType>(Callee->getType());
8887 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8888 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00008889 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00008890 // See if we can optimize any arguments passed through the varargs area of
8891 // the call.
8892 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00008893 E = CS.arg_end(); I != E; ++I, ++ix) {
8894 CastInst *CI = dyn_cast<CastInst>(*I);
8895 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8896 *I = CI->getOperand(0);
8897 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00008898 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00008899 }
Chris Lattner6c266db2003-10-07 22:54:13 +00008900 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008901
Duncan Sandsf0c33542007-12-19 21:13:37 +00008902 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008903 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008904 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008905 Changed = true;
8906 }
8907
Chris Lattner6c266db2003-10-07 22:54:13 +00008908 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008909}
8910
Chris Lattner9fe38862003-06-19 17:00:31 +00008911// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8912// attempt to move the cast to the arguments of the call/invoke.
8913//
8914bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8915 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8916 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008917 if (CE->getOpcode() != Instruction::BitCast ||
8918 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008919 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008920 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008921 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008922 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008923
8924 // Okay, this is a cast from a function to a different type. Unless doing so
8925 // would cause a type conversion of one of our arguments, change this call to
8926 // be a direct call with arguments casted to the appropriate types.
8927 //
8928 const FunctionType *FT = Callee->getFunctionType();
8929 const Type *OldRetTy = Caller->getType();
8930
Devang Patel75e6f022008-03-11 18:04:06 +00008931 if (isa<StructType>(FT->getReturnType()))
8932 return false; // TODO: Handle multiple return values.
8933
Chris Lattnerf78616b2004-01-14 06:06:08 +00008934 // Check to see if we are changing the return type...
8935 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008936 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008937 // Conversion is ok if changing from pointer to int of same size.
8938 !(isa<PointerType>(FT->getReturnType()) &&
8939 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008940 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008941
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008942 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008943 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008944 FT->getReturnType() != Type::VoidTy &&
8945 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008946 return false; // Cannot transform this return value.
8947
Chris Lattner58d74912008-03-12 17:45:29 +00008948 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8949 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008950 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8951 return false; // Attribute not compatible with transformed value.
8952 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008953
Chris Lattnerf78616b2004-01-14 06:06:08 +00008954 // If the callsite is an invoke instruction, and the return value is used by
8955 // a PHI node in a successor, we cannot change the return type of the call
8956 // because there is no place to put the cast instruction (without breaking
8957 // the critical edge). Bail out in this case.
8958 if (!Caller->use_empty())
8959 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8960 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8961 UI != E; ++UI)
8962 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8963 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008964 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008965 return false;
8966 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008967
8968 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8969 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008970
Chris Lattner9fe38862003-06-19 17:00:31 +00008971 CallSite::arg_iterator AI = CS.arg_begin();
8972 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8973 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008974 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008975
8976 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008977 return false; // Cannot transform this parameter value.
8978
Chris Lattner58d74912008-03-12 17:45:29 +00008979 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8980 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008981
Reid Spencer3da59db2006-11-27 01:05:10 +00008982 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008983 // Some conversions are safe even if we do not have a body.
8984 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008985 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008986 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008987 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008988 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8989 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008990 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008991 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008992 }
8993
8994 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008995 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008996 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008997
Chris Lattner58d74912008-03-12 17:45:29 +00008998 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8999 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009000 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009001 // won't be dropping them. Check that these extra arguments have attributes
9002 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009003 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9004 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009005 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009006 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009007 if (PAttrs & ParamAttr::VarArgsIncompatible)
9008 return false;
9009 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009010
Chris Lattner9fe38862003-06-19 17:00:31 +00009011 // Okay, we decided that this is a safe thing to do: go ahead and start
9012 // inserting cast instructions as necessary...
9013 std::vector<Value*> Args;
9014 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009015 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009016 attrVec.reserve(NumCommonArgs);
9017
9018 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009019 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009020
9021 // If the return value is not being used, the type may not be compatible
9022 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009023 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009024
9025 // Add the new return attributes.
9026 if (RAttrs)
9027 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009028
9029 AI = CS.arg_begin();
9030 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9031 const Type *ParamTy = FT->getParamType(i);
9032 if ((*AI)->getType() == ParamTy) {
9033 Args.push_back(*AI);
9034 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009035 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009036 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00009037 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009038 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009039 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009040
9041 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009042 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009043 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009044 }
9045
9046 // If the function takes more arguments than the call was taking, add them
9047 // now...
9048 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9049 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9050
9051 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009052 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009053 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009054 cerr << "WARNING: While resolving call to function '"
9055 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009056 } else {
9057 // Add all of the arguments in their promoted form to the arg list...
9058 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9059 const Type *PTy = getPromotedType((*AI)->getType());
9060 if (PTy != (*AI)->getType()) {
9061 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009062 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9063 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00009064 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009065 InsertNewInstBefore(Cast, *Caller);
9066 Args.push_back(Cast);
9067 } else {
9068 Args.push_back(*AI);
9069 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009070
Duncan Sandse1e520f2008-01-13 08:02:44 +00009071 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009072 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009073 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9074 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009075 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009076 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009077
9078 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009079 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009080
Chris Lattner58d74912008-03-12 17:45:29 +00009081 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009082
Chris Lattner9fe38862003-06-19 17:00:31 +00009083 Instruction *NC;
9084 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009085 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9086 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009087 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009088 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009089 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009090 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9091 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009092 CallInst *CI = cast<CallInst>(Caller);
9093 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009094 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009095 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009096 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009097 }
9098
Chris Lattner6934a042007-02-11 01:23:03 +00009099 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009100 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009101 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009102 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009103 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009104 OldRetTy, false);
9105 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009106
9107 // If this is an invoke instruction, we should insert it after the first
9108 // non-phi, instruction in the normal successor block.
9109 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9110 BasicBlock::iterator I = II->getNormalDest()->begin();
9111 while (isa<PHINode>(I)) ++I;
9112 InsertNewInstBefore(NC, *I);
9113 } else {
9114 // Otherwise, it's a call, just insert cast right after the call instr
9115 InsertNewInstBefore(NC, *Caller);
9116 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009117 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009118 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009119 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009120 }
9121 }
9122
9123 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9124 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009125 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009126 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009127 return true;
9128}
9129
Duncan Sandscdb6d922007-09-17 10:26:40 +00009130// transformCallThroughTrampoline - Turn a call to a function created by the
9131// init_trampoline intrinsic into a direct call to the underlying function.
9132//
9133Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9134 Value *Callee = CS.getCalledValue();
9135 const PointerType *PTy = cast<PointerType>(Callee->getType());
9136 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009137 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009138
9139 // If the call already has the 'nest' attribute somewhere then give up -
9140 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009141 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009142 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009143
9144 IntrinsicInst *Tramp =
9145 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9146
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009147 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009148 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9149 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9150
Chris Lattner58d74912008-03-12 17:45:29 +00009151 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9152 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009153 unsigned NestIdx = 1;
9154 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009155 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009156
9157 // Look for a parameter marked with the 'nest' attribute.
9158 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9159 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009160 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009161 // Record the parameter type and any other attributes.
9162 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009163 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009164 break;
9165 }
9166
9167 if (NestTy) {
9168 Instruction *Caller = CS.getInstruction();
9169 std::vector<Value*> NewArgs;
9170 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9171
Chris Lattner58d74912008-03-12 17:45:29 +00009172 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9173 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009174
Duncan Sandscdb6d922007-09-17 10:26:40 +00009175 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009176 // mean appending it. Likewise for attributes.
9177
9178 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009179 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9180 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009181
Duncan Sandscdb6d922007-09-17 10:26:40 +00009182 {
9183 unsigned Idx = 1;
9184 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9185 do {
9186 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009187 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009188 Value *NestVal = Tramp->getOperand(3);
9189 if (NestVal->getType() != NestTy)
9190 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9191 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009192 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009193 }
9194
9195 if (I == E)
9196 break;
9197
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009198 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009199 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009200 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009201 NewAttrs.push_back
9202 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009203
9204 ++Idx, ++I;
9205 } while (1);
9206 }
9207
9208 // The trampoline may have been bitcast to a bogus type (FTy).
9209 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009210 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009211
Duncan Sandscdb6d922007-09-17 10:26:40 +00009212 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009213 NewTypes.reserve(FTy->getNumParams()+1);
9214
Duncan Sandscdb6d922007-09-17 10:26:40 +00009215 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009216 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009217 {
9218 unsigned Idx = 1;
9219 FunctionType::param_iterator I = FTy->param_begin(),
9220 E = FTy->param_end();
9221
9222 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009223 if (Idx == NestIdx)
9224 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009225 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009226
9227 if (I == E)
9228 break;
9229
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009230 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009231 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009232
9233 ++Idx, ++I;
9234 } while (1);
9235 }
9236
9237 // Replace the trampoline call with a direct call. Let the generic
9238 // code sort out any function type mismatches.
9239 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009240 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009241 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9242 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009243 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009244
9245 Instruction *NewCaller;
9246 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009247 NewCaller = InvokeInst::Create(NewCallee,
9248 II->getNormalDest(), II->getUnwindDest(),
9249 NewArgs.begin(), NewArgs.end(),
9250 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009251 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009252 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009253 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009254 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9255 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009256 if (cast<CallInst>(Caller)->isTailCall())
9257 cast<CallInst>(NewCaller)->setTailCall();
9258 cast<CallInst>(NewCaller)->
9259 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009260 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009261 }
9262 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9263 Caller->replaceAllUsesWith(NewCaller);
9264 Caller->eraseFromParent();
9265 RemoveFromWorkList(Caller);
9266 return 0;
9267 }
9268 }
9269
9270 // Replace the trampoline call with a direct call. Since there is no 'nest'
9271 // parameter, there is no need to adjust the argument list. Let the generic
9272 // code sort out any function type mismatches.
9273 Constant *NewCallee =
9274 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9275 CS.setCalledFunction(NewCallee);
9276 return CS.getInstruction();
9277}
9278
Chris Lattner7da52b22006-11-01 04:51:18 +00009279/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9280/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9281/// and a single binop.
9282Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9283 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009284 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9285 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009286 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009287 Value *LHSVal = FirstInst->getOperand(0);
9288 Value *RHSVal = FirstInst->getOperand(1);
9289
9290 const Type *LHSType = LHSVal->getType();
9291 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009292
9293 // Scan to see if all operands are the same opcode, all have one use, and all
9294 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009295 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009296 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009297 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009298 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009299 // types or GEP's with different index types.
9300 I->getOperand(0)->getType() != LHSType ||
9301 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009302 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009303
9304 // If they are CmpInst instructions, check their predicates
9305 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9306 if (cast<CmpInst>(I)->getPredicate() !=
9307 cast<CmpInst>(FirstInst)->getPredicate())
9308 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009309
9310 // Keep track of which operand needs a phi node.
9311 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9312 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009313 }
9314
Chris Lattner53738a42006-11-08 19:42:28 +00009315 // Otherwise, this is safe to transform, determine if it is profitable.
9316
9317 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9318 // Indexes are often folded into load/store instructions, so we don't want to
9319 // hide them behind a phi.
9320 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9321 return 0;
9322
Chris Lattner7da52b22006-11-01 04:51:18 +00009323 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009324 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009325 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009326 if (LHSVal == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00009327 NewLHS = PHINode::Create(LHSType, FirstInst->getOperand(0)->getName()+".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009328 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9329 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009330 InsertNewInstBefore(NewLHS, PN);
9331 LHSVal = NewLHS;
9332 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009333
9334 if (RHSVal == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00009335 NewRHS = PHINode::Create(RHSType, FirstInst->getOperand(1)->getName()+".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009336 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9337 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009338 InsertNewInstBefore(NewRHS, PN);
9339 RHSVal = NewRHS;
9340 }
9341
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009342 // Add all operands to the new PHIs.
9343 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9344 if (NewLHS) {
9345 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9346 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9347 }
9348 if (NewRHS) {
9349 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9350 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9351 }
9352 }
9353
Chris Lattner7da52b22006-11-01 04:51:18 +00009354 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00009355 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009356 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9357 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
9358 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009359 else {
9360 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009361 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009362 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009363}
9364
Chris Lattner76c73142006-11-01 07:13:54 +00009365/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9366/// of the block that defines it. This means that it must be obvious the value
9367/// of the load is not changed from the point of the load to the end of the
9368/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009369///
9370/// Finally, it is safe, but not profitable, to sink a load targetting a
9371/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9372/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009373static bool isSafeToSinkLoad(LoadInst *L) {
9374 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9375
9376 for (++BBI; BBI != E; ++BBI)
9377 if (BBI->mayWriteToMemory())
9378 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009379
9380 // Check for non-address taken alloca. If not address-taken already, it isn't
9381 // profitable to do this xform.
9382 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9383 bool isAddressTaken = false;
9384 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9385 UI != E; ++UI) {
9386 if (isa<LoadInst>(UI)) continue;
9387 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9388 // If storing TO the alloca, then the address isn't taken.
9389 if (SI->getOperand(1) == AI) continue;
9390 }
9391 isAddressTaken = true;
9392 break;
9393 }
9394
9395 if (!isAddressTaken)
9396 return false;
9397 }
9398
Chris Lattner76c73142006-11-01 07:13:54 +00009399 return true;
9400}
9401
Chris Lattner9fe38862003-06-19 17:00:31 +00009402
Chris Lattnerbac32862004-11-14 19:13:23 +00009403// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9404// operator and they all are only used by the PHI, PHI together their
9405// inputs, and do the operation once, to the result of the PHI.
9406Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9407 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9408
9409 // Scan the instruction, looking for input operations that can be folded away.
9410 // If all input operands to the phi are the same instruction (e.g. a cast from
9411 // the same type or "+42") we can pull the operation through the PHI, reducing
9412 // code size and simplifying code.
9413 Constant *ConstantOp = 0;
9414 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009415 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009416 if (isa<CastInst>(FirstInst)) {
9417 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009418 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009419 // Can fold binop, compare or shift here if the RHS is a constant,
9420 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009421 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009422 if (ConstantOp == 0)
9423 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009424 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9425 isVolatile = LI->isVolatile();
9426 // We can't sink the load if the loaded value could be modified between the
9427 // load and the PHI.
9428 if (LI->getParent() != PN.getIncomingBlock(0) ||
9429 !isSafeToSinkLoad(LI))
9430 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009431 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009432 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009433 return FoldPHIArgBinOpIntoPHI(PN);
9434 // Can't handle general GEPs yet.
9435 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009436 } else {
9437 return 0; // Cannot fold this operation.
9438 }
9439
9440 // Check to see if all arguments are the same operation.
9441 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9442 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9443 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009444 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009445 return 0;
9446 if (CastSrcTy) {
9447 if (I->getOperand(0)->getType() != CastSrcTy)
9448 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009449 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009450 // We can't sink the load if the loaded value could be modified between
9451 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009452 if (LI->isVolatile() != isVolatile ||
9453 LI->getParent() != PN.getIncomingBlock(i) ||
9454 !isSafeToSinkLoad(LI))
9455 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009456
9457 // If the PHI is volatile and its block has multiple successors, sinking
9458 // it would remove a load of the volatile value from the path through the
9459 // other successor.
9460 if (isVolatile &&
9461 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9462 return 0;
9463
9464
Chris Lattnerbac32862004-11-14 19:13:23 +00009465 } else if (I->getOperand(1) != ConstantOp) {
9466 return 0;
9467 }
9468 }
9469
9470 // Okay, they are all the same operation. Create a new PHI node of the
9471 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009472 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9473 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009474 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009475
9476 Value *InVal = FirstInst->getOperand(0);
9477 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009478
9479 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009480 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9481 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9482 if (NewInVal != InVal)
9483 InVal = 0;
9484 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9485 }
9486
9487 Value *PhiVal;
9488 if (InVal) {
9489 // The new PHI unions all of the same values together. This is really
9490 // common, so we handle it intelligently here for compile-time speed.
9491 PhiVal = InVal;
9492 delete NewPN;
9493 } else {
9494 InsertNewInstBefore(NewPN, PN);
9495 PhiVal = NewPN;
9496 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009497
Chris Lattnerbac32862004-11-14 19:13:23 +00009498 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009499 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9500 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009501 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00009502 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009503 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Reid Spencere4d87aa2006-12-23 06:05:41 +00009504 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
9505 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009506 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9507
9508 // If this was a volatile load that we are merging, make sure to loop through
9509 // and mark all the input loads as non-volatile. If we don't do this, we will
9510 // insert a new volatile load and the old ones will not be deletable.
9511 if (isVolatile)
9512 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9513 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9514
9515 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009516}
Chris Lattnera1be5662002-05-02 17:06:02 +00009517
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009518/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9519/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009520static bool DeadPHICycle(PHINode *PN,
9521 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009522 if (PN->use_empty()) return true;
9523 if (!PN->hasOneUse()) return false;
9524
9525 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009526 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009527 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009528
9529 // Don't scan crazily complex things.
9530 if (PotentiallyDeadPHIs.size() == 16)
9531 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009532
9533 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9534 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009535
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009536 return false;
9537}
9538
Chris Lattnercf5008a2007-11-06 21:52:06 +00009539/// PHIsEqualValue - Return true if this phi node is always equal to
9540/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9541/// z = some value; x = phi (y, z); y = phi (x, z)
9542static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9543 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9544 // See if we already saw this PHI node.
9545 if (!ValueEqualPHIs.insert(PN))
9546 return true;
9547
9548 // Don't scan crazily complex things.
9549 if (ValueEqualPHIs.size() == 16)
9550 return false;
9551
9552 // Scan the operands to see if they are either phi nodes or are equal to
9553 // the value.
9554 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9555 Value *Op = PN->getIncomingValue(i);
9556 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9557 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9558 return false;
9559 } else if (Op != NonPhiInVal)
9560 return false;
9561 }
9562
9563 return true;
9564}
9565
9566
Chris Lattner473945d2002-05-06 18:06:38 +00009567// PHINode simplification
9568//
Chris Lattner7e708292002-06-25 16:13:24 +00009569Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009570 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009571 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009572
Owen Anderson7e057142006-07-10 22:03:18 +00009573 if (Value *V = PN.hasConstantValue())
9574 return ReplaceInstUsesWith(PN, V);
9575
Owen Anderson7e057142006-07-10 22:03:18 +00009576 // If all PHI operands are the same operation, pull them through the PHI,
9577 // reducing code size.
9578 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9579 PN.getIncomingValue(0)->hasOneUse())
9580 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9581 return Result;
9582
9583 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9584 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9585 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009586 if (PN.hasOneUse()) {
9587 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9588 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009589 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009590 PotentiallyDeadPHIs.insert(&PN);
9591 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9592 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9593 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009594
9595 // If this phi has a single use, and if that use just computes a value for
9596 // the next iteration of a loop, delete the phi. This occurs with unused
9597 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9598 // common case here is good because the only other things that catch this
9599 // are induction variable analysis (sometimes) and ADCE, which is only run
9600 // late.
9601 if (PHIUser->hasOneUse() &&
9602 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9603 PHIUser->use_back() == &PN) {
9604 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9605 }
9606 }
Owen Anderson7e057142006-07-10 22:03:18 +00009607
Chris Lattnercf5008a2007-11-06 21:52:06 +00009608 // We sometimes end up with phi cycles that non-obviously end up being the
9609 // same value, for example:
9610 // z = some value; x = phi (y, z); y = phi (x, z)
9611 // where the phi nodes don't necessarily need to be in the same block. Do a
9612 // quick check to see if the PHI node only contains a single non-phi value, if
9613 // so, scan to see if the phi cycle is actually equal to that value.
9614 {
9615 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9616 // Scan for the first non-phi operand.
9617 while (InValNo != NumOperandVals &&
9618 isa<PHINode>(PN.getIncomingValue(InValNo)))
9619 ++InValNo;
9620
9621 if (InValNo != NumOperandVals) {
9622 Value *NonPhiInVal = PN.getOperand(InValNo);
9623
9624 // Scan the rest of the operands to see if there are any conflicts, if so
9625 // there is no need to recursively scan other phis.
9626 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9627 Value *OpVal = PN.getIncomingValue(InValNo);
9628 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9629 break;
9630 }
9631
9632 // If we scanned over all operands, then we have one unique value plus
9633 // phi values. Scan PHI nodes to see if they all merge in each other or
9634 // the value.
9635 if (InValNo == NumOperandVals) {
9636 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9637 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9638 return ReplaceInstUsesWith(PN, NonPhiInVal);
9639 }
9640 }
9641 }
Chris Lattner60921c92003-12-19 05:58:40 +00009642 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009643}
9644
Reid Spencer17212df2006-12-12 09:18:51 +00009645static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9646 Instruction *InsertPoint,
9647 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009648 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9649 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009650 // We must cast correctly to the pointer type. Ensure that we
9651 // sign extend the integer value if it is smaller as this is
9652 // used for address computation.
9653 Instruction::CastOps opcode =
9654 (VTySize < PtrSize ? Instruction::SExt :
9655 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9656 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009657}
9658
Chris Lattnera1be5662002-05-02 17:06:02 +00009659
Chris Lattner7e708292002-06-25 16:13:24 +00009660Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009661 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009662 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009663 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009664 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009665 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009666
Chris Lattnere87597f2004-10-16 18:11:37 +00009667 if (isa<UndefValue>(GEP.getOperand(0)))
9668 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9669
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009670 bool HasZeroPointerIndex = false;
9671 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9672 HasZeroPointerIndex = C->isNullValue();
9673
9674 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009675 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009676
Chris Lattner28977af2004-04-05 01:30:19 +00009677 // Eliminate unneeded casts for indices.
9678 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009679
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009680 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009681 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009682 if (isa<SequentialType>(*GTI)) {
9683 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009684 if (CI->getOpcode() == Instruction::ZExt ||
9685 CI->getOpcode() == Instruction::SExt) {
9686 const Type *SrcTy = CI->getOperand(0)->getType();
9687 // We can eliminate a cast from i32 to i64 iff the target
9688 // is a 32-bit pointer target.
9689 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9690 MadeChange = true;
9691 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009692 }
9693 }
9694 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009695 // If we are using a wider index than needed for this platform, shrink it
9696 // to what we need. If the incoming value needs a cast instruction,
9697 // insert it. This explicit cast can make subsequent optimizations more
9698 // obvious.
9699 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009700 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009701 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009702 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009703 MadeChange = true;
9704 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009705 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9706 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009707 GEP.setOperand(i, Op);
9708 MadeChange = true;
9709 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009710 }
Chris Lattner28977af2004-04-05 01:30:19 +00009711 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009712 }
Chris Lattner28977af2004-04-05 01:30:19 +00009713 if (MadeChange) return &GEP;
9714
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009715 // If this GEP instruction doesn't move the pointer, and if the input operand
9716 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9717 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009718 if (GEP.hasAllZeroIndices()) {
9719 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9720 // If the bitcast is of an allocation, and the allocation will be
9721 // converted to match the type of the cast, don't touch this.
9722 if (isa<AllocationInst>(BCI->getOperand(0))) {
9723 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009724 if (Instruction *I = visitBitCast(*BCI)) {
9725 if (I != BCI) {
9726 I->takeName(BCI);
9727 BCI->getParent()->getInstList().insert(BCI, I);
9728 ReplaceInstUsesWith(*BCI, I);
9729 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009730 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009731 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009732 }
9733 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9734 }
9735 }
9736
Chris Lattner90ac28c2002-08-02 19:29:35 +00009737 // Combine Indices - If the source pointer to this getelementptr instruction
9738 // is a getelementptr instruction, combine the indices of the two
9739 // getelementptr instructions into a single instruction.
9740 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009741 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009742 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009743 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009744
9745 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009746 // Note that if our source is a gep chain itself that we wait for that
9747 // chain to be resolved before we perform this transformation. This
9748 // avoids us creating a TON of code in some cases.
9749 //
9750 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9751 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9752 return 0; // Wait until our source is folded to completion.
9753
Chris Lattner72588fc2007-02-15 22:48:32 +00009754 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009755
9756 // Find out whether the last index in the source GEP is a sequential idx.
9757 bool EndsWithSequential = false;
9758 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9759 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009760 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009761
Chris Lattner90ac28c2002-08-02 19:29:35 +00009762 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009763 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009764 // Replace: gep (gep %P, long B), long A, ...
9765 // With: T = long A+B; gep %P, T, ...
9766 //
Chris Lattner620ce142004-05-07 22:09:22 +00009767 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009768 if (SO1 == Constant::getNullValue(SO1->getType())) {
9769 Sum = GO1;
9770 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9771 Sum = SO1;
9772 } else {
9773 // If they aren't the same type, convert both to an integer of the
9774 // target's pointer size.
9775 if (SO1->getType() != GO1->getType()) {
9776 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009777 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009778 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009779 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009780 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009781 unsigned PS = TD->getPointerSizeInBits();
9782 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009783 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009784 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009785
Duncan Sands514ab342007-11-01 20:53:16 +00009786 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009787 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009788 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009789 } else {
9790 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009791 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9792 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009793 }
9794 }
9795 }
Chris Lattner620ce142004-05-07 22:09:22 +00009796 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9797 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9798 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009799 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9800 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009801 }
Chris Lattner28977af2004-04-05 01:30:19 +00009802 }
Chris Lattner620ce142004-05-07 22:09:22 +00009803
9804 // Recycle the GEP we already have if possible.
9805 if (SrcGEPOperands.size() == 2) {
9806 GEP.setOperand(0, SrcGEPOperands[0]);
9807 GEP.setOperand(1, Sum);
9808 return &GEP;
9809 } else {
9810 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9811 SrcGEPOperands.end()-1);
9812 Indices.push_back(Sum);
9813 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9814 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009815 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009816 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009817 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009818 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009819 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9820 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009821 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9822 }
9823
9824 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009825 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9826 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009827
Chris Lattner620ce142004-05-07 22:09:22 +00009828 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009829 // GEP of global variable. If all of the indices for this GEP are
9830 // constants, we can promote this to a constexpr instead of an instruction.
9831
9832 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009833 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009834 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9835 for (; I != E && isa<Constant>(*I); ++I)
9836 Indices.push_back(cast<Constant>(*I));
9837
9838 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009839 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9840 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009841
9842 // Replace all uses of the GEP with the new constexpr...
9843 return ReplaceInstUsesWith(GEP, CE);
9844 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009845 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009846 if (!isa<PointerType>(X->getType())) {
9847 // Not interesting. Source pointer must be a cast from pointer.
9848 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009849 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9850 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009851 //
9852 // This occurs when the program declares an array extern like "int X[];"
9853 //
9854 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9855 const PointerType *XTy = cast<PointerType>(X->getType());
9856 if (const ArrayType *XATy =
9857 dyn_cast<ArrayType>(XTy->getElementType()))
9858 if (const ArrayType *CATy =
9859 dyn_cast<ArrayType>(CPTy->getElementType()))
9860 if (CATy->getElementType() == XATy->getElementType()) {
9861 // At this point, we know that the cast source type is a pointer
9862 // to an array of the same type as the destination pointer
9863 // array. Because the array type is never stepped over (there
9864 // is a leading zero) we can fold the cast into this GEP.
9865 GEP.setOperand(0, X);
9866 return &GEP;
9867 }
9868 } else if (GEP.getNumOperands() == 2) {
9869 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009870 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9871 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009872 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9873 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9874 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009875 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9876 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009877 Value *Idx[2];
9878 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9879 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009880 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009881 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009882 // V and GEP are both pointer types --> BitCast
9883 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009884 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009885
9886 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009887 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009888 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009889 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009890
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009891 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009892 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009893 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009894
9895 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9896 // allow either a mul, shift, or constant here.
9897 Value *NewIdx = 0;
9898 ConstantInt *Scale = 0;
9899 if (ArrayEltSize == 1) {
9900 NewIdx = GEP.getOperand(1);
9901 Scale = ConstantInt::get(NewIdx->getType(), 1);
9902 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009903 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009904 Scale = CI;
9905 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9906 if (Inst->getOpcode() == Instruction::Shl &&
9907 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009908 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9909 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9910 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009911 NewIdx = Inst->getOperand(0);
9912 } else if (Inst->getOpcode() == Instruction::Mul &&
9913 isa<ConstantInt>(Inst->getOperand(1))) {
9914 Scale = cast<ConstantInt>(Inst->getOperand(1));
9915 NewIdx = Inst->getOperand(0);
9916 }
9917 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009918
Chris Lattner7835cdd2005-09-13 18:36:04 +00009919 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009920 // out, perform the transformation. Note, we don't know whether Scale is
9921 // signed or not. We'll use unsigned version of division/modulo
9922 // operation after making sure Scale doesn't have the sign bit set.
9923 if (Scale && Scale->getSExtValue() >= 0LL &&
9924 Scale->getZExtValue() % ArrayEltSize == 0) {
9925 Scale = ConstantInt::get(Scale->getType(),
9926 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009927 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009928 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009929 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009930 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9931 NewIdx = InsertNewInstBefore(Sc, GEP);
9932 }
9933
9934 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009935 Value *Idx[2];
9936 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9937 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009938 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009939 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009940 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9941 // The NewGEP must be pointer typed, so must the old one -> BitCast
9942 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009943 }
9944 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009945 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009946 }
9947
Chris Lattner8a2a3112001-12-14 16:52:21 +00009948 return 0;
9949}
9950
Chris Lattner0864acf2002-11-04 16:18:53 +00009951Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9952 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009953 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009954 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9955 const Type *NewTy =
9956 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009957 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009958
9959 // Create and insert the replacement instruction...
9960 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009961 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009962 else {
9963 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009964 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009965 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009966
9967 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009968
Chris Lattner0864acf2002-11-04 16:18:53 +00009969 // Scan to the end of the allocation instructions, to skip over a block of
9970 // allocas if possible...
9971 //
9972 BasicBlock::iterator It = New;
9973 while (isa<AllocationInst>(*It)) ++It;
9974
9975 // Now that I is pointing to the first non-allocation-inst in the block,
9976 // insert our getelementptr instruction...
9977 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009978 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009979 Value *Idx[2];
9980 Idx[0] = NullIdx;
9981 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +00009982 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9983 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009984
9985 // Now make everything use the getelementptr instead of the original
9986 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009987 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009988 } else if (isa<UndefValue>(AI.getArraySize())) {
9989 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009990 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009991 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009992
9993 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9994 // Note that we only do this for alloca's, because malloc should allocate and
9995 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009996 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009997 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009998 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9999
Chris Lattner0864acf2002-11-04 16:18:53 +000010000 return 0;
10001}
10002
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010003Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10004 Value *Op = FI.getOperand(0);
10005
Chris Lattner17be6352004-10-18 02:59:09 +000010006 // free undef -> unreachable.
10007 if (isa<UndefValue>(Op)) {
10008 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010009 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010010 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010011 return EraseInstFromFunction(FI);
10012 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010013
Chris Lattner6160e852004-02-28 04:57:37 +000010014 // If we have 'free null' delete the instruction. This can happen in stl code
10015 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010016 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010017 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010018
10019 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10020 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10021 FI.setOperand(0, CI->getOperand(0));
10022 return &FI;
10023 }
10024
10025 // Change free (gep X, 0,0,0,0) into free(X)
10026 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10027 if (GEPI->hasAllZeroIndices()) {
10028 AddToWorkList(GEPI);
10029 FI.setOperand(0, GEPI->getOperand(0));
10030 return &FI;
10031 }
10032 }
10033
10034 // Change free(malloc) into nothing, if the malloc has a single use.
10035 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10036 if (MI->hasOneUse()) {
10037 EraseInstFromFunction(FI);
10038 return EraseInstFromFunction(*MI);
10039 }
Chris Lattner6160e852004-02-28 04:57:37 +000010040
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010041 return 0;
10042}
10043
10044
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010045/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010046static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010047 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010048 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010049 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010050
Devang Patel99db6ad2007-10-18 19:52:32 +000010051 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10052 // Instead of loading constant c string, use corresponding integer value
10053 // directly if string length is small enough.
10054 const std::string &Str = CE->getOperand(0)->getStringValue();
10055 if (!Str.empty()) {
10056 unsigned len = Str.length();
10057 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10058 unsigned numBits = Ty->getPrimitiveSizeInBits();
10059 // Replace LI with immediate integer store.
10060 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010061 APInt StrVal(numBits, 0);
10062 APInt SingleChar(numBits, 0);
10063 if (TD->isLittleEndian()) {
10064 for (signed i = len-1; i >= 0; i--) {
10065 SingleChar = (uint64_t) Str[i];
10066 StrVal = (StrVal << 8) | SingleChar;
10067 }
10068 } else {
10069 for (unsigned i = 0; i < len; i++) {
10070 SingleChar = (uint64_t) Str[i];
10071 StrVal = (StrVal << 8) | SingleChar;
10072 }
10073 // Append NULL at the end.
10074 SingleChar = 0;
10075 StrVal = (StrVal << 8) | SingleChar;
10076 }
10077 Value *NL = ConstantInt::get(StrVal);
10078 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010079 }
10080 }
10081 }
10082
Chris Lattnerb89e0712004-07-13 01:49:43 +000010083 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010084 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010085 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010086
Reid Spencer42230162007-01-22 05:51:25 +000010087 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010088 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010089 // If the source is an array, the code below will not succeed. Check to
10090 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10091 // constants.
10092 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10093 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10094 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010095 Value *Idxs[2];
10096 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10097 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010098 SrcTy = cast<PointerType>(CastOp->getType());
10099 SrcPTy = SrcTy->getElementType();
10100 }
10101
Reid Spencer42230162007-01-22 05:51:25 +000010102 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010103 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010104 // Do not allow turning this into a load of an integer, which is then
10105 // casted to a pointer, this pessimizes pointer analysis a lot.
10106 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010107 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10108 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010109
Chris Lattnerf9527852005-01-31 04:50:46 +000010110 // Okay, we are casting from one integer or pointer type to another of
10111 // the same size. Instead of casting the pointer before the load, cast
10112 // the result of the loaded value.
10113 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10114 CI->getName(),
10115 LI.isVolatile()),LI);
10116 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010117 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010118 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010119 }
10120 }
10121 return 0;
10122}
10123
Chris Lattnerc10aced2004-09-19 18:43:46 +000010124/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010125/// from this value cannot trap. If it is not obviously safe to load from the
10126/// specified pointer, we do a quick local scan of the basic block containing
10127/// ScanFrom, to determine if the address is already accessed.
10128static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010129 // If it is an alloca it is always safe to load from.
10130 if (isa<AllocaInst>(V)) return true;
10131
Duncan Sands46318cd2007-09-19 10:25:38 +000010132 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010133 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010134 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010135 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010136
10137 // Otherwise, be a little bit agressive by scanning the local block where we
10138 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010139 // from/to. If so, the previous load or store would have already trapped,
10140 // so there is no harm doing an extra load (also, CSE will later eliminate
10141 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010142 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10143
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010144 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010145 --BBI;
10146
10147 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10148 if (LI->getOperand(0) == V) return true;
10149 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10150 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010151
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010152 }
Chris Lattner8a375202004-09-19 19:18:10 +000010153 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010154}
10155
Chris Lattner8d2e8882007-08-11 18:48:48 +000010156/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10157/// until we find the underlying object a pointer is referring to or something
10158/// we don't understand. Note that the returned pointer may be offset from the
10159/// input, because we ignore GEP indices.
10160static Value *GetUnderlyingObject(Value *Ptr) {
10161 while (1) {
10162 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10163 if (CE->getOpcode() == Instruction::BitCast ||
10164 CE->getOpcode() == Instruction::GetElementPtr)
10165 Ptr = CE->getOperand(0);
10166 else
10167 return Ptr;
10168 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10169 Ptr = BCI->getOperand(0);
10170 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10171 Ptr = GEP->getOperand(0);
10172 } else {
10173 return Ptr;
10174 }
10175 }
10176}
10177
Chris Lattner833b8a42003-06-26 05:06:25 +000010178Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10179 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010180
Dan Gohman9941f742007-07-20 16:34:21 +000010181 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010182 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10183 if (KnownAlign >
10184 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10185 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010186 LI.setAlignment(KnownAlign);
10187
Chris Lattner37366c12005-05-01 04:24:53 +000010188 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010189 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010190 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010191 return Res;
10192
10193 // None of the following transforms are legal for volatile loads.
10194 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010195
Chris Lattner62f254d2005-09-12 22:00:15 +000010196 if (&LI.getParent()->front() != &LI) {
10197 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010198 // If the instruction immediately before this is a store to the same
10199 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010200 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10201 if (SI->getOperand(1) == LI.getOperand(0))
10202 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010203 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10204 if (LIB->getOperand(0) == LI.getOperand(0))
10205 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010206 }
Chris Lattner37366c12005-05-01 04:24:53 +000010207
Christopher Lambb15147e2007-12-29 07:56:53 +000010208 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10209 const Value *GEPI0 = GEPI->getOperand(0);
10210 // TODO: Consider a target hook for valid address spaces for this xform.
10211 if (isa<ConstantPointerNull>(GEPI0) &&
10212 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010213 // Insert a new store to null instruction before the load to indicate
10214 // that this code is not reachable. We do this instead of inserting
10215 // an unreachable instruction directly because we cannot modify the
10216 // CFG.
10217 new StoreInst(UndefValue::get(LI.getType()),
10218 Constant::getNullValue(Op->getType()), &LI);
10219 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10220 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010221 }
Chris Lattner37366c12005-05-01 04:24:53 +000010222
Chris Lattnere87597f2004-10-16 18:11:37 +000010223 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010224 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010225 // TODO: Consider a target hook for valid address spaces for this xform.
10226 if (isa<UndefValue>(C) || (C->isNullValue() &&
10227 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010228 // Insert a new store to null instruction before the load to indicate that
10229 // this code is not reachable. We do this instead of inserting an
10230 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010231 new StoreInst(UndefValue::get(LI.getType()),
10232 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010233 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010234 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010235
Chris Lattnere87597f2004-10-16 18:11:37 +000010236 // Instcombine load (constant global) into the value loaded.
10237 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010238 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010239 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010240
Chris Lattnere87597f2004-10-16 18:11:37 +000010241 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010242 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010243 if (CE->getOpcode() == Instruction::GetElementPtr) {
10244 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010245 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010246 if (Constant *V =
10247 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010248 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010249 if (CE->getOperand(0)->isNullValue()) {
10250 // Insert a new store to null instruction before the load to indicate
10251 // that this code is not reachable. We do this instead of inserting
10252 // an unreachable instruction directly because we cannot modify the
10253 // CFG.
10254 new StoreInst(UndefValue::get(LI.getType()),
10255 Constant::getNullValue(Op->getType()), &LI);
10256 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10257 }
10258
Reid Spencer3da59db2006-11-27 01:05:10 +000010259 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010260 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010261 return Res;
10262 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010263 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010264 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010265
10266 // If this load comes from anywhere in a constant global, and if the global
10267 // is all undef or zero, we know what it loads.
10268 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10269 if (GV->isConstant() && GV->hasInitializer()) {
10270 if (GV->getInitializer()->isNullValue())
10271 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10272 else if (isa<UndefValue>(GV->getInitializer()))
10273 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10274 }
10275 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010276
Chris Lattner37366c12005-05-01 04:24:53 +000010277 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010278 // Change select and PHI nodes to select values instead of addresses: this
10279 // helps alias analysis out a lot, allows many others simplifications, and
10280 // exposes redundancy in the code.
10281 //
10282 // Note that we cannot do the transformation unless we know that the
10283 // introduced loads cannot trap! Something like this is valid as long as
10284 // the condition is always false: load (select bool %C, int* null, int* %G),
10285 // but it would not be valid if we transformed it to load from null
10286 // unconditionally.
10287 //
10288 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10289 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010290 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10291 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010292 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010293 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010294 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010295 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010296 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010297 }
10298
Chris Lattner684fe212004-09-23 15:46:00 +000010299 // load (select (cond, null, P)) -> load P
10300 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10301 if (C->isNullValue()) {
10302 LI.setOperand(0, SI->getOperand(2));
10303 return &LI;
10304 }
10305
10306 // load (select (cond, P, null)) -> load P
10307 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10308 if (C->isNullValue()) {
10309 LI.setOperand(0, SI->getOperand(1));
10310 return &LI;
10311 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010312 }
10313 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010314 return 0;
10315}
10316
Reid Spencer55af2b52007-01-19 21:20:31 +000010317/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010318/// when possible.
10319static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10320 User *CI = cast<User>(SI.getOperand(1));
10321 Value *CastOp = CI->getOperand(0);
10322
10323 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10324 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10325 const Type *SrcPTy = SrcTy->getElementType();
10326
Reid Spencer42230162007-01-22 05:51:25 +000010327 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010328 // If the source is an array, the code below will not succeed. Check to
10329 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10330 // constants.
10331 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10332 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10333 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010334 Value* Idxs[2];
10335 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10336 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010337 SrcTy = cast<PointerType>(CastOp->getType());
10338 SrcPTy = SrcTy->getElementType();
10339 }
10340
Reid Spencer67f827c2007-01-20 23:35:48 +000010341 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10342 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10343 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010344
10345 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010346 // the same size. Instead of casting the pointer before
10347 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010348 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010349 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010350 Instruction::CastOps opcode = Instruction::BitCast;
10351 const Type* CastSrcTy = SIOp0->getType();
10352 const Type* CastDstTy = SrcPTy;
10353 if (isa<PointerType>(CastDstTy)) {
10354 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010355 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010356 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010357 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010358 opcode = Instruction::PtrToInt;
10359 }
10360 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010361 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010362 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010363 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +000010364 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
10365 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010366 return new StoreInst(NewCast, CastOp);
10367 }
10368 }
10369 }
10370 return 0;
10371}
10372
Chris Lattner2f503e62005-01-31 05:36:43 +000010373Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10374 Value *Val = SI.getOperand(0);
10375 Value *Ptr = SI.getOperand(1);
10376
10377 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010378 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010379 ++NumCombined;
10380 return 0;
10381 }
Chris Lattner836692d2007-01-15 06:51:56 +000010382
10383 // If the RHS is an alloca with a single use, zapify the store, making the
10384 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010385 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010386 if (isa<AllocaInst>(Ptr)) {
10387 EraseInstFromFunction(SI);
10388 ++NumCombined;
10389 return 0;
10390 }
10391
10392 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10393 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10394 GEP->getOperand(0)->hasOneUse()) {
10395 EraseInstFromFunction(SI);
10396 ++NumCombined;
10397 return 0;
10398 }
10399 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010400
Dan Gohman9941f742007-07-20 16:34:21 +000010401 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010402 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10403 if (KnownAlign >
10404 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10405 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010406 SI.setAlignment(KnownAlign);
10407
Chris Lattner9ca96412006-02-08 03:25:32 +000010408 // Do really simple DSE, to catch cases where there are several consequtive
10409 // stores to the same location, separated by a few arithmetic operations. This
10410 // situation often occurs with bitfield accesses.
10411 BasicBlock::iterator BBI = &SI;
10412 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10413 --ScanInsts) {
10414 --BBI;
10415
10416 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10417 // Prev store isn't volatile, and stores to the same location?
10418 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10419 ++NumDeadStore;
10420 ++BBI;
10421 EraseInstFromFunction(*PrevSI);
10422 continue;
10423 }
10424 break;
10425 }
10426
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010427 // If this is a load, we have to stop. However, if the loaded value is from
10428 // the pointer we're loading and is producing the pointer we're storing,
10429 // then *this* store is dead (X = load P; store X -> P).
10430 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010431 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010432 EraseInstFromFunction(SI);
10433 ++NumCombined;
10434 return 0;
10435 }
10436 // Otherwise, this is a load from some other location. Stores before it
10437 // may not be dead.
10438 break;
10439 }
10440
Chris Lattner9ca96412006-02-08 03:25:32 +000010441 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010442 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010443 break;
10444 }
10445
10446
10447 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010448
10449 // store X, null -> turns into 'unreachable' in SimplifyCFG
10450 if (isa<ConstantPointerNull>(Ptr)) {
10451 if (!isa<UndefValue>(Val)) {
10452 SI.setOperand(0, UndefValue::get(Val->getType()));
10453 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010454 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010455 ++NumCombined;
10456 }
10457 return 0; // Do not modify these!
10458 }
10459
10460 // store undef, Ptr -> noop
10461 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010462 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010463 ++NumCombined;
10464 return 0;
10465 }
10466
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010467 // If the pointer destination is a cast, see if we can fold the cast into the
10468 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010469 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010470 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10471 return Res;
10472 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010473 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010474 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10475 return Res;
10476
Chris Lattner408902b2005-09-12 23:23:25 +000010477
10478 // If this store is the last instruction in the basic block, and if the block
10479 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010480 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010481 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010482 if (BI->isUnconditional())
10483 if (SimplifyStoreAtEndOfBlock(SI))
10484 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010485
Chris Lattner2f503e62005-01-31 05:36:43 +000010486 return 0;
10487}
10488
Chris Lattner3284d1f2007-04-15 00:07:55 +000010489/// SimplifyStoreAtEndOfBlock - Turn things like:
10490/// if () { *P = v1; } else { *P = v2 }
10491/// into a phi node with a store in the successor.
10492///
Chris Lattner31755a02007-04-15 01:02:18 +000010493/// Simplify things like:
10494/// *P = v1; if () { *P = v2; }
10495/// into a phi node with a store in the successor.
10496///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010497bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10498 BasicBlock *StoreBB = SI.getParent();
10499
10500 // Check to see if the successor block has exactly two incoming edges. If
10501 // so, see if the other predecessor contains a store to the same location.
10502 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010503 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010504
10505 // Determine whether Dest has exactly two predecessors and, if so, compute
10506 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010507 pred_iterator PI = pred_begin(DestBB);
10508 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010509 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010510 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010511 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010512 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010513 return false;
10514
10515 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010516 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010517 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010518 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010519 }
Chris Lattner31755a02007-04-15 01:02:18 +000010520 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010521 return false;
10522
10523
Chris Lattner31755a02007-04-15 01:02:18 +000010524 // Verify that the other block ends in a branch and is not otherwise empty.
10525 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010526 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010527 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010528 return false;
10529
Chris Lattner31755a02007-04-15 01:02:18 +000010530 // If the other block ends in an unconditional branch, check for the 'if then
10531 // else' case. there is an instruction before the branch.
10532 StoreInst *OtherStore = 0;
10533 if (OtherBr->isUnconditional()) {
10534 // If this isn't a store, or isn't a store to the same location, bail out.
10535 --BBI;
10536 OtherStore = dyn_cast<StoreInst>(BBI);
10537 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10538 return false;
10539 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010540 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010541 // destinations is StoreBB, then we have the if/then case.
10542 if (OtherBr->getSuccessor(0) != StoreBB &&
10543 OtherBr->getSuccessor(1) != StoreBB)
10544 return false;
10545
10546 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010547 // if/then triangle. See if there is a store to the same ptr as SI that
10548 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010549 for (;; --BBI) {
10550 // Check to see if we find the matching store.
10551 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10552 if (OtherStore->getOperand(1) != SI.getOperand(1))
10553 return false;
10554 break;
10555 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010556 // If we find something that may be using the stored value, or if we run
10557 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010558 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10559 BBI == OtherBB->begin())
10560 return false;
10561 }
10562
10563 // In order to eliminate the store in OtherBr, we have to
10564 // make sure nothing reads the stored value in StoreBB.
10565 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10566 // FIXME: This should really be AA driven.
10567 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10568 return false;
10569 }
10570 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010571
Chris Lattner31755a02007-04-15 01:02:18 +000010572 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010573 Value *MergedVal = OtherStore->getOperand(0);
10574 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010575 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010576 PN->reserveOperandSpace(2);
10577 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010578 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10579 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010580 }
10581
10582 // Advance to a place where it is safe to insert the new store and
10583 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010584 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010585 while (isa<PHINode>(BBI)) ++BBI;
10586 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10587 OtherStore->isVolatile()), *BBI);
10588
10589 // Nuke the old stores.
10590 EraseInstFromFunction(SI);
10591 EraseInstFromFunction(*OtherStore);
10592 ++NumCombined;
10593 return true;
10594}
10595
Chris Lattner2f503e62005-01-31 05:36:43 +000010596
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010597Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10598 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010599 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010600 BasicBlock *TrueDest;
10601 BasicBlock *FalseDest;
10602 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10603 !isa<Constant>(X)) {
10604 // Swap Destinations and condition...
10605 BI.setCondition(X);
10606 BI.setSuccessor(0, FalseDest);
10607 BI.setSuccessor(1, TrueDest);
10608 return &BI;
10609 }
10610
Reid Spencere4d87aa2006-12-23 06:05:41 +000010611 // Cannonicalize fcmp_one -> fcmp_oeq
10612 FCmpInst::Predicate FPred; Value *Y;
10613 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10614 TrueDest, FalseDest)))
10615 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10616 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10617 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010618 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010619 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10620 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010621 // Swap Destinations and condition...
10622 BI.setCondition(NewSCC);
10623 BI.setSuccessor(0, FalseDest);
10624 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010625 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010626 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010627 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010628 return &BI;
10629 }
10630
10631 // Cannonicalize icmp_ne -> icmp_eq
10632 ICmpInst::Predicate IPred;
10633 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10634 TrueDest, FalseDest)))
10635 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10636 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10637 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10638 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010639 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010640 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10641 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010642 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010643 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010644 BI.setSuccessor(0, FalseDest);
10645 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010646 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010647 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010648 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010649 return &BI;
10650 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010651
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010652 return 0;
10653}
Chris Lattner0864acf2002-11-04 16:18:53 +000010654
Chris Lattner46238a62004-07-03 00:26:11 +000010655Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10656 Value *Cond = SI.getCondition();
10657 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10658 if (I->getOpcode() == Instruction::Add)
10659 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10660 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10661 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010662 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010663 AddRHS));
10664 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010665 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010666 return &SI;
10667 }
10668 }
10669 return 0;
10670}
10671
Chris Lattner220b0cf2006-03-05 00:22:33 +000010672/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10673/// is to leave as a vector operation.
10674static bool CheapToScalarize(Value *V, bool isConstant) {
10675 if (isa<ConstantAggregateZero>(V))
10676 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010677 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010678 if (isConstant) return true;
10679 // If all elts are the same, we can extract.
10680 Constant *Op0 = C->getOperand(0);
10681 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10682 if (C->getOperand(i) != Op0)
10683 return false;
10684 return true;
10685 }
10686 Instruction *I = dyn_cast<Instruction>(V);
10687 if (!I) return false;
10688
10689 // Insert element gets simplified to the inserted element or is deleted if
10690 // this is constant idx extract element and its a constant idx insertelt.
10691 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10692 isa<ConstantInt>(I->getOperand(2)))
10693 return true;
10694 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10695 return true;
10696 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10697 if (BO->hasOneUse() &&
10698 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10699 CheapToScalarize(BO->getOperand(1), isConstant)))
10700 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010701 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10702 if (CI->hasOneUse() &&
10703 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10704 CheapToScalarize(CI->getOperand(1), isConstant)))
10705 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010706
10707 return false;
10708}
10709
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010710/// Read and decode a shufflevector mask.
10711///
10712/// It turns undef elements into values that are larger than the number of
10713/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010714static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10715 unsigned NElts = SVI->getType()->getNumElements();
10716 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10717 return std::vector<unsigned>(NElts, 0);
10718 if (isa<UndefValue>(SVI->getOperand(2)))
10719 return std::vector<unsigned>(NElts, 2*NElts);
10720
10721 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010722 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010723 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10724 if (isa<UndefValue>(CP->getOperand(i)))
10725 Result.push_back(NElts*2); // undef -> 8
10726 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010727 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010728 return Result;
10729}
10730
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010731/// FindScalarElement - Given a vector and an element number, see if the scalar
10732/// value is already around as a register, for example if it were inserted then
10733/// extracted from the vector.
10734static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010735 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10736 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010737 unsigned Width = PTy->getNumElements();
10738 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010739 return UndefValue::get(PTy->getElementType());
10740
10741 if (isa<UndefValue>(V))
10742 return UndefValue::get(PTy->getElementType());
10743 else if (isa<ConstantAggregateZero>(V))
10744 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010745 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010746 return CP->getOperand(EltNo);
10747 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10748 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010749 if (!isa<ConstantInt>(III->getOperand(2)))
10750 return 0;
10751 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010752
10753 // If this is an insert to the element we are looking for, return the
10754 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010755 if (EltNo == IIElt)
10756 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010757
10758 // Otherwise, the insertelement doesn't modify the value, recurse on its
10759 // vector input.
10760 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010761 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010762 unsigned InEl = getShuffleMask(SVI)[EltNo];
10763 if (InEl < Width)
10764 return FindScalarElement(SVI->getOperand(0), InEl);
10765 else if (InEl < Width*2)
10766 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10767 else
10768 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010769 }
10770
10771 // Otherwise, we don't know.
10772 return 0;
10773}
10774
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010775Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010776
Dan Gohman07a96762007-07-16 14:29:03 +000010777 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010778 if (isa<UndefValue>(EI.getOperand(0)))
10779 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10780
Dan Gohman07a96762007-07-16 14:29:03 +000010781 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010782 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10783 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10784
Reid Spencer9d6565a2007-02-15 02:26:10 +000010785 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010786 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010787 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010788 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010789 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010790 if (C->getOperand(i) != op0) {
10791 op0 = 0;
10792 break;
10793 }
10794 if (op0)
10795 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010796 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010797
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010798 // If extracting a specified index from the vector, see if we can recursively
10799 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010800 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010801 unsigned IndexVal = IdxC->getZExtValue();
10802 unsigned VectorWidth =
10803 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10804
10805 // If this is extracting an invalid index, turn this into undef, to avoid
10806 // crashing the code below.
10807 if (IndexVal >= VectorWidth)
10808 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10809
Chris Lattner867b99f2006-10-05 06:55:50 +000010810 // This instruction only demands the single element from the input vector.
10811 // If the input vector has a single use, simplify it based on this use
10812 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010813 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010814 uint64_t UndefElts;
10815 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010816 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010817 UndefElts)) {
10818 EI.setOperand(0, V);
10819 return &EI;
10820 }
10821 }
10822
Reid Spencerb83eb642006-10-20 07:07:24 +000010823 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010824 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010825
10826 // If the this extractelement is directly using a bitcast from a vector of
10827 // the same number of elements, see if we can find the source element from
10828 // it. In this case, we will end up needing to bitcast the scalars.
10829 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10830 if (const VectorType *VT =
10831 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10832 if (VT->getNumElements() == VectorWidth)
10833 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10834 return new BitCastInst(Elt, EI.getType());
10835 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010836 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010837
Chris Lattner73fa49d2006-05-25 22:53:38 +000010838 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010839 if (I->hasOneUse()) {
10840 // Push extractelement into predecessor operation if legal and
10841 // profitable to do so
10842 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010843 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10844 if (CheapToScalarize(BO, isConstantElt)) {
10845 ExtractElementInst *newEI0 =
10846 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10847 EI.getName()+".lhs");
10848 ExtractElementInst *newEI1 =
10849 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10850 EI.getName()+".rhs");
10851 InsertNewInstBefore(newEI0, EI);
10852 InsertNewInstBefore(newEI1, EI);
10853 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10854 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010855 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010856 unsigned AS =
10857 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010858 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10859 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010860 GetElementPtrInst *GEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010861 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010862 InsertNewInstBefore(GEP, EI);
10863 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010864 }
10865 }
10866 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10867 // Extracting the inserted element?
10868 if (IE->getOperand(2) == EI.getOperand(1))
10869 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10870 // If the inserted and extracted elements are constants, they must not
10871 // be the same value, extract from the pre-inserted value instead.
10872 if (isa<Constant>(IE->getOperand(2)) &&
10873 isa<Constant>(EI.getOperand(1))) {
10874 AddUsesToWorkList(EI);
10875 EI.setOperand(0, IE->getOperand(0));
10876 return &EI;
10877 }
10878 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10879 // If this is extracting an element from a shufflevector, figure out where
10880 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010881 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10882 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010883 Value *Src;
10884 if (SrcIdx < SVI->getType()->getNumElements())
10885 Src = SVI->getOperand(0);
10886 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10887 SrcIdx -= SVI->getType()->getNumElements();
10888 Src = SVI->getOperand(1);
10889 } else {
10890 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010891 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010892 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010893 }
10894 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010895 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010896 return 0;
10897}
10898
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010899/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10900/// elements from either LHS or RHS, return the shuffle mask and true.
10901/// Otherwise, return false.
10902static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10903 std::vector<Constant*> &Mask) {
10904 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10905 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010906 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010907
10908 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010909 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010910 return true;
10911 } else if (V == LHS) {
10912 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010913 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010914 return true;
10915 } else if (V == RHS) {
10916 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010917 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010918 return true;
10919 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10920 // If this is an insert of an extract from some other vector, include it.
10921 Value *VecOp = IEI->getOperand(0);
10922 Value *ScalarOp = IEI->getOperand(1);
10923 Value *IdxOp = IEI->getOperand(2);
10924
Chris Lattnerd929f062006-04-27 21:14:21 +000010925 if (!isa<ConstantInt>(IdxOp))
10926 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010927 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010928
10929 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10930 // Okay, we can handle this if the vector we are insertinting into is
10931 // transitively ok.
10932 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10933 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010934 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010935 return true;
10936 }
10937 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10938 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010939 EI->getOperand(0)->getType() == V->getType()) {
10940 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010941 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010942
10943 // This must be extracting from either LHS or RHS.
10944 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10945 // Okay, we can handle this if the vector we are insertinting into is
10946 // transitively ok.
10947 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10948 // If so, update the mask to reflect the inserted value.
10949 if (EI->getOperand(0) == LHS) {
10950 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010951 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010952 } else {
10953 assert(EI->getOperand(0) == RHS);
10954 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010955 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010956
10957 }
10958 return true;
10959 }
10960 }
10961 }
10962 }
10963 }
10964 // TODO: Handle shufflevector here!
10965
10966 return false;
10967}
10968
10969/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10970/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10971/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010972static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010973 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010974 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010975 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010976 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010977 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010978
10979 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010980 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010981 return V;
10982 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010983 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010984 return V;
10985 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10986 // If this is an insert of an extract from some other vector, include it.
10987 Value *VecOp = IEI->getOperand(0);
10988 Value *ScalarOp = IEI->getOperand(1);
10989 Value *IdxOp = IEI->getOperand(2);
10990
10991 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10992 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10993 EI->getOperand(0)->getType() == V->getType()) {
10994 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010995 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10996 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010997
10998 // Either the extracted from or inserted into vector must be RHSVec,
10999 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011000 if (EI->getOperand(0) == RHS || RHS == 0) {
11001 RHS = EI->getOperand(0);
11002 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011003 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011004 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011005 return V;
11006 }
11007
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011008 if (VecOp == RHS) {
11009 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011010 // Everything but the extracted element is replaced with the RHS.
11011 for (unsigned i = 0; i != NumElts; ++i) {
11012 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011013 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011014 }
11015 return V;
11016 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011017
11018 // If this insertelement is a chain that comes from exactly these two
11019 // vectors, return the vector and the effective shuffle.
11020 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11021 return EI->getOperand(0);
11022
Chris Lattnerefb47352006-04-15 01:39:45 +000011023 }
11024 }
11025 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011026 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011027
11028 // Otherwise, can't do anything fancy. Return an identity vector.
11029 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011030 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011031 return V;
11032}
11033
11034Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11035 Value *VecOp = IE.getOperand(0);
11036 Value *ScalarOp = IE.getOperand(1);
11037 Value *IdxOp = IE.getOperand(2);
11038
Chris Lattner599ded12007-04-09 01:11:16 +000011039 // Inserting an undef or into an undefined place, remove this.
11040 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11041 ReplaceInstUsesWith(IE, VecOp);
11042
Chris Lattnerefb47352006-04-15 01:39:45 +000011043 // If the inserted element was extracted from some other vector, and if the
11044 // indexes are constant, try to turn this into a shufflevector operation.
11045 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11046 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11047 EI->getOperand(0)->getType() == IE.getType()) {
11048 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011049 unsigned ExtractedIdx =
11050 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011051 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011052
11053 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11054 return ReplaceInstUsesWith(IE, VecOp);
11055
11056 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11057 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11058
11059 // If we are extracting a value from a vector, then inserting it right
11060 // back into the same place, just use the input vector.
11061 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11062 return ReplaceInstUsesWith(IE, VecOp);
11063
11064 // We could theoretically do this for ANY input. However, doing so could
11065 // turn chains of insertelement instructions into a chain of shufflevector
11066 // instructions, and right now we do not merge shufflevectors. As such,
11067 // only do this in a situation where it is clear that there is benefit.
11068 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11069 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11070 // the values of VecOp, except then one read from EIOp0.
11071 // Build a new shuffle mask.
11072 std::vector<Constant*> Mask;
11073 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011074 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011075 else {
11076 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011077 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011078 NumVectorElts));
11079 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011080 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011081 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011082 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011083 }
11084
11085 // If this insertelement isn't used by some other insertelement, turn it
11086 // (and any insertelements it points to), into one big shuffle.
11087 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11088 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011089 Value *RHS = 0;
11090 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11091 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11092 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011093 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011094 }
11095 }
11096 }
11097
11098 return 0;
11099}
11100
11101
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011102Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11103 Value *LHS = SVI.getOperand(0);
11104 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011105 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011106
11107 bool MadeChange = false;
11108
Chris Lattner867b99f2006-10-05 06:55:50 +000011109 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011110 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011111 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11112
Chris Lattnere4929dd2007-01-05 07:36:08 +000011113 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011114 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011115 if (isa<UndefValue>(SVI.getOperand(1))) {
11116 // Scan to see if there are any references to the RHS. If so, replace them
11117 // with undef element refs and set MadeChange to true.
11118 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11119 if (Mask[i] >= e && Mask[i] != 2*e) {
11120 Mask[i] = 2*e;
11121 MadeChange = true;
11122 }
11123 }
11124
11125 if (MadeChange) {
11126 // Remap any references to RHS to use LHS.
11127 std::vector<Constant*> Elts;
11128 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11129 if (Mask[i] == 2*e)
11130 Elts.push_back(UndefValue::get(Type::Int32Ty));
11131 else
11132 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11133 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011134 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011135 }
11136 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011137
Chris Lattner863bcff2006-05-25 23:48:38 +000011138 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11139 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11140 if (LHS == RHS || isa<UndefValue>(LHS)) {
11141 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011142 // shuffle(undef,undef,mask) -> undef.
11143 return ReplaceInstUsesWith(SVI, LHS);
11144 }
11145
Chris Lattner863bcff2006-05-25 23:48:38 +000011146 // Remap any references to RHS to use LHS.
11147 std::vector<Constant*> Elts;
11148 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011149 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011150 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011151 else {
11152 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11153 (Mask[i] < e && isa<UndefValue>(LHS)))
11154 Mask[i] = 2*e; // Turn into undef.
11155 else
11156 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011157 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011158 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011159 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011160 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011161 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011162 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011163 LHS = SVI.getOperand(0);
11164 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011165 MadeChange = true;
11166 }
11167
Chris Lattner7b2e27922006-05-26 00:29:06 +000011168 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011169 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011170
Chris Lattner863bcff2006-05-25 23:48:38 +000011171 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11172 if (Mask[i] >= e*2) continue; // Ignore undef values.
11173 // Is this an identity shuffle of the LHS value?
11174 isLHSID &= (Mask[i] == i);
11175
11176 // Is this an identity shuffle of the RHS value?
11177 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011178 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011179
Chris Lattner863bcff2006-05-25 23:48:38 +000011180 // Eliminate identity shuffles.
11181 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11182 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011183
Chris Lattner7b2e27922006-05-26 00:29:06 +000011184 // If the LHS is a shufflevector itself, see if we can combine it with this
11185 // one without producing an unusual shuffle. Here we are really conservative:
11186 // we are absolutely afraid of producing a shuffle mask not in the input
11187 // program, because the code gen may not be smart enough to turn a merged
11188 // shuffle into two specific shuffles: it may produce worse code. As such,
11189 // we only merge two shuffles if the result is one of the two input shuffle
11190 // masks. In this case, merging the shuffles just removes one instruction,
11191 // which we know is safe. This is good for things like turning:
11192 // (splat(splat)) -> splat.
11193 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11194 if (isa<UndefValue>(RHS)) {
11195 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11196
11197 std::vector<unsigned> NewMask;
11198 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11199 if (Mask[i] >= 2*e)
11200 NewMask.push_back(2*e);
11201 else
11202 NewMask.push_back(LHSMask[Mask[i]]);
11203
11204 // If the result mask is equal to the src shuffle or this shuffle mask, do
11205 // the replacement.
11206 if (NewMask == LHSMask || NewMask == Mask) {
11207 std::vector<Constant*> Elts;
11208 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11209 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011210 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011211 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011212 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011213 }
11214 }
11215 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11216 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011217 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011218 }
11219 }
11220 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011221
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011222 return MadeChange ? &SVI : 0;
11223}
11224
11225
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011226
Chris Lattnerea1c4542004-12-08 23:43:58 +000011227
11228/// TryToSinkInstruction - Try to move the specified instruction from its
11229/// current block into the beginning of DestBlock, which can only happen if it's
11230/// safe to move the instruction past all of the instructions between it and the
11231/// end of its block.
11232static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11233 assert(I->hasOneUse() && "Invariants didn't hold!");
11234
Chris Lattner108e9022005-10-27 17:13:11 +000011235 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011236 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11237 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011238
Chris Lattnerea1c4542004-12-08 23:43:58 +000011239 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011240 if (isa<AllocaInst>(I) && I->getParent() ==
11241 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011242 return false;
11243
Chris Lattner96a52a62004-12-09 07:14:34 +000011244 // We can only sink load instructions if there is nothing between the load and
11245 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011246 if (I->mayReadFromMemory()) {
11247 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011248 Scan != E; ++Scan)
11249 if (Scan->mayWriteToMemory())
11250 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011251 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011252
11253 BasicBlock::iterator InsertPos = DestBlock->begin();
11254 while (isa<PHINode>(InsertPos)) ++InsertPos;
11255
Chris Lattner4bc5f802005-08-08 19:11:57 +000011256 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011257 ++NumSunkInst;
11258 return true;
11259}
11260
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011261
11262/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11263/// all reachable code to the worklist.
11264///
11265/// This has a couple of tricks to make the code faster and more powerful. In
11266/// particular, we constant fold and DCE instructions as we go, to avoid adding
11267/// them to the worklist (this significantly speeds up instcombine on code where
11268/// many instructions are dead or constant). Additionally, if we find a branch
11269/// whose condition is a known constant, we only visit the reachable successors.
11270///
11271static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011272 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011273 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011274 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011275 std::vector<BasicBlock*> Worklist;
11276 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011277
Chris Lattner2c7718a2007-03-23 19:17:18 +000011278 while (!Worklist.empty()) {
11279 BB = Worklist.back();
11280 Worklist.pop_back();
11281
11282 // We have now visited this block! If we've already been here, ignore it.
11283 if (!Visited.insert(BB)) continue;
11284
11285 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11286 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011287
Chris Lattner2c7718a2007-03-23 19:17:18 +000011288 // DCE instruction if trivially dead.
11289 if (isInstructionTriviallyDead(Inst)) {
11290 ++NumDeadInst;
11291 DOUT << "IC: DCE: " << *Inst;
11292 Inst->eraseFromParent();
11293 continue;
11294 }
11295
11296 // ConstantProp instruction if trivially constant.
11297 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11298 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11299 Inst->replaceAllUsesWith(C);
11300 ++NumConstProp;
11301 Inst->eraseFromParent();
11302 continue;
11303 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011304
Chris Lattner2c7718a2007-03-23 19:17:18 +000011305 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011306 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011307
11308 // Recursively visit successors. If this is a branch or switch on a
11309 // constant, only visit the reachable successor.
11310 TerminatorInst *TI = BB->getTerminator();
11311 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11312 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11313 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011314 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011315 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011316 continue;
11317 }
11318 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11319 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11320 // See if this is an explicit destination.
11321 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11322 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011323 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011324 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011325 continue;
11326 }
11327
11328 // Otherwise it is the default destination.
11329 Worklist.push_back(SI->getSuccessor(0));
11330 continue;
11331 }
11332 }
11333
11334 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11335 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011336 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011337}
11338
Chris Lattnerec9c3582007-03-03 02:04:50 +000011339bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011340 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011341 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011342
11343 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11344 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011345
Chris Lattnerb3d59702005-07-07 20:40:38 +000011346 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011347 // Do a depth-first traversal of the function, populate the worklist with
11348 // the reachable instructions. Ignore blocks that are not reachable. Keep
11349 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011350 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011351 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011352
Chris Lattnerb3d59702005-07-07 20:40:38 +000011353 // Do a quick scan over the function. If we find any blocks that are
11354 // unreachable, remove any instructions inside of them. This prevents
11355 // the instcombine code from having to deal with some bad special cases.
11356 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11357 if (!Visited.count(BB)) {
11358 Instruction *Term = BB->getTerminator();
11359 while (Term != BB->begin()) { // Remove instrs bottom-up
11360 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011361
Bill Wendlingb7427032006-11-26 09:46:52 +000011362 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011363 ++NumDeadInst;
11364
11365 if (!I->use_empty())
11366 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11367 I->eraseFromParent();
11368 }
11369 }
11370 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011371
Chris Lattnerdbab3862007-03-02 21:28:56 +000011372 while (!Worklist.empty()) {
11373 Instruction *I = RemoveOneFromWorkList();
11374 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011375
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011376 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011377 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011378 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011379 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011380 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011381 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011382
Bill Wendlingb7427032006-11-26 09:46:52 +000011383 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011384
11385 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011386 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011387 continue;
11388 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011389
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011390 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011391 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011392 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011393
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011394 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011395 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011396 ReplaceInstUsesWith(*I, C);
11397
Chris Lattner62b14df2002-09-02 04:59:56 +000011398 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011399 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011400 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011401 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011402 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011403
Chris Lattnerea1c4542004-12-08 23:43:58 +000011404 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011405 // FIXME: Remove GetResultInst test when first class support for aggregates
11406 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011407 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011408 BasicBlock *BB = I->getParent();
11409 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11410 if (UserParent != BB) {
11411 bool UserIsSuccessor = false;
11412 // See if the user is one of our successors.
11413 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11414 if (*SI == UserParent) {
11415 UserIsSuccessor = true;
11416 break;
11417 }
11418
11419 // If the user is one of our immediate successors, and if that successor
11420 // only has us as a predecessors (we'd have to split the critical edge
11421 // otherwise), we can keep going.
11422 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11423 next(pred_begin(UserParent)) == pred_end(UserParent))
11424 // Okay, the CFG is simple enough, try to sink this instruction.
11425 Changed |= TryToSinkInstruction(I, UserParent);
11426 }
11427 }
11428
Chris Lattner8a2a3112001-12-14 16:52:21 +000011429 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011430#ifndef NDEBUG
11431 std::string OrigI;
11432#endif
11433 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011434 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011435 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011436 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011437 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011438 DOUT << "IC: Old = " << *I
11439 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011440
Chris Lattnerf523d062004-06-09 05:08:07 +000011441 // Everything uses the new instruction now.
11442 I->replaceAllUsesWith(Result);
11443
11444 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011445 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011446 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011447
Chris Lattner6934a042007-02-11 01:23:03 +000011448 // Move the name to the new instruction first.
11449 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011450
11451 // Insert the new instruction into the basic block...
11452 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011453 BasicBlock::iterator InsertPos = I;
11454
11455 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11456 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11457 ++InsertPos;
11458
11459 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011460
Chris Lattner00d51312004-05-01 23:27:23 +000011461 // Make sure that we reprocess all operands now that we reduced their
11462 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011463 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011464
Chris Lattnerf523d062004-06-09 05:08:07 +000011465 // Instructions can end up on the worklist more than once. Make sure
11466 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011467 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011468
11469 // Erase the old instruction.
11470 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011471 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011472#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011473 DOUT << "IC: Mod = " << OrigI
11474 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011475#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011476
Chris Lattner90ac28c2002-08-02 19:29:35 +000011477 // If the instruction was modified, it's possible that it is now dead.
11478 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011479 if (isInstructionTriviallyDead(I)) {
11480 // Make sure we process all operands now that we are reducing their
11481 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011482 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011483
Chris Lattner00d51312004-05-01 23:27:23 +000011484 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011485 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011486 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011487 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011488 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011489 AddToWorkList(I);
11490 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011491 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011492 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011493 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011494 }
11495 }
11496
Chris Lattnerec9c3582007-03-03 02:04:50 +000011497 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011498
11499 // Do an explicit clear, this shrinks the map if needed.
11500 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011501 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011502}
11503
Chris Lattnerec9c3582007-03-03 02:04:50 +000011504
11505bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011506 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11507
Chris Lattnerec9c3582007-03-03 02:04:50 +000011508 bool EverMadeChange = false;
11509
11510 // Iterate while there is work to do.
11511 unsigned Iteration = 0;
11512 while (DoOneIteration(F, Iteration++))
11513 EverMadeChange = true;
11514 return EverMadeChange;
11515}
11516
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011517FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011518 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011519}
Brian Gaeked0fde302003-11-11 22:41:34 +000011520