blob: 10627ea6e925efa74d407c82d5a5ee77a4cf6f37 [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);
373
Chris Lattnerafe91a52006-06-15 19:07:26 +0000374
Reid Spencerc55b2432006-12-13 18:21:21 +0000375 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000376
377 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
378 APInt& KnownOne, unsigned Depth = 0);
379 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
380 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
381 unsigned CastOpc,
382 int &NumCastsRemoved);
383 unsigned GetOrEnforceKnownAlignment(Value *V,
384 unsigned PrefAlign = 0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000385 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000386
Devang Patel19974732007-05-03 01:11:54 +0000387 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000388 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000389}
390
Chris Lattner4f98c562003-03-10 21:43:22 +0000391// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000392// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000393static unsigned getComplexity(Value *V) {
394 if (isa<Instruction>(V)) {
395 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000396 return 3;
397 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000398 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000399 if (isa<Argument>(V)) return 3;
400 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000401}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000402
Chris Lattnerc8802d22003-03-11 00:12:48 +0000403// isOnlyUse - Return true if this instruction will be deleted if we stop using
404// it.
405static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000406 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000407}
408
Chris Lattner4cb170c2004-02-23 06:38:22 +0000409// getPromotedType - Return the specified type promoted as it would be to pass
410// though a va_arg area...
411static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000412 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
413 if (ITy->getBitWidth() < 32)
414 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000415 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000416 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000417}
418
Reid Spencer3da59db2006-11-27 01:05:10 +0000419/// getBitCastOperand - If the specified operand is a CastInst or a constant
420/// expression bitcast, return the operand value, otherwise return null.
421static Value *getBitCastOperand(Value *V) {
422 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000423 return I->getOperand(0);
424 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000425 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000426 return CE->getOperand(0);
427 return 0;
428}
429
Reid Spencer3da59db2006-11-27 01:05:10 +0000430/// This function is a wrapper around CastInst::isEliminableCastPair. It
431/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000432static Instruction::CastOps
433isEliminableCastPair(
434 const CastInst *CI, ///< The first cast instruction
435 unsigned opcode, ///< The opcode of the second cast instruction
436 const Type *DstTy, ///< The target type for the second cast instruction
437 TargetData *TD ///< The target data for pointer size
438) {
439
440 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
441 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000442
Reid Spencer3da59db2006-11-27 01:05:10 +0000443 // Get the opcodes of the two Cast instructions
444 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
445 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000446
Reid Spencer3da59db2006-11-27 01:05:10 +0000447 return Instruction::CastOps(
448 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
449 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000450}
451
452/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
453/// in any code being generated. It does not require codegen if V is simple
454/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000455static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
456 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000457 if (V->getType() == Ty || isa<Constant>(V)) return false;
458
Chris Lattner01575b72006-05-25 23:24:33 +0000459 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000460 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000461 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000462 return false;
463 return true;
464}
465
466/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
467/// InsertBefore instruction. This is specialized a bit to avoid inserting
468/// casts that are known to not do anything...
469///
Reid Spencer17212df2006-12-12 09:18:51 +0000470Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
471 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000472 Instruction *InsertBefore) {
473 if (V->getType() == DestTy) return V;
474 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000475 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000476
Reid Spencer17212df2006-12-12 09:18:51 +0000477 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000478}
479
Chris Lattner4f98c562003-03-10 21:43:22 +0000480// SimplifyCommutative - This performs a few simplifications for commutative
481// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000482//
Chris Lattner4f98c562003-03-10 21:43:22 +0000483// 1. Order operands such that they are listed from right (least complex) to
484// left (most complex). This puts constants before unary operators before
485// binary operators.
486//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000487// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
488// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000489//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000490bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000491 bool Changed = false;
492 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
493 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000494
Chris Lattner4f98c562003-03-10 21:43:22 +0000495 if (!I.isAssociative()) return Changed;
496 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000497 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
498 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
499 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000500 Constant *Folded = ConstantExpr::get(I.getOpcode(),
501 cast<Constant>(I.getOperand(1)),
502 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000503 I.setOperand(0, Op->getOperand(0));
504 I.setOperand(1, Folded);
505 return true;
506 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
507 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
508 isOnlyUse(Op) && isOnlyUse(Op1)) {
509 Constant *C1 = cast<Constant>(Op->getOperand(1));
510 Constant *C2 = cast<Constant>(Op1->getOperand(1));
511
512 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000513 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000514 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
515 Op1->getOperand(0),
516 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000517 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000518 I.setOperand(0, New);
519 I.setOperand(1, Folded);
520 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000521 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000522 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000523 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000524}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000525
Reid Spencere4d87aa2006-12-23 06:05:41 +0000526/// SimplifyCompare - For a CmpInst this function just orders the operands
527/// so that theyare listed from right (least complex) to left (most complex).
528/// This puts constants before unary operators before binary operators.
529bool InstCombiner::SimplifyCompare(CmpInst &I) {
530 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
531 return false;
532 I.swapOperands();
533 // Compare instructions are not associative so there's nothing else we can do.
534 return true;
535}
536
Chris Lattner8d969642003-03-10 23:06:50 +0000537// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
538// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000539//
Chris Lattner8d969642003-03-10 23:06:50 +0000540static inline Value *dyn_castNegVal(Value *V) {
541 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000542 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000543
Chris Lattner0ce85802004-12-14 20:08:06 +0000544 // Constants can be considered to be negated values if they can be folded.
545 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
546 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000547 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000548}
549
Chris Lattner8d969642003-03-10 23:06:50 +0000550static inline Value *dyn_castNotVal(Value *V) {
551 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000552 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000553
554 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000555 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000556 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000557 return 0;
558}
559
Chris Lattnerc8802d22003-03-11 00:12:48 +0000560// dyn_castFoldableMul - If this value is a multiply that can be folded into
561// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000562// non-constant operand of the multiply, and set CST to point to the multiplier.
563// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000564//
Chris Lattner50af16a2004-11-13 19:50:12 +0000565static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000566 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000567 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000568 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000569 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000570 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000571 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000572 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000573 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000574 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000575 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000576 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000577 return I->getOperand(0);
578 }
579 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000580 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000581}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000582
Chris Lattner574da9b2005-01-13 20:14:25 +0000583/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
584/// expression, return it.
585static User *dyn_castGetElementPtr(Value *V) {
586 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
587 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
588 if (CE->getOpcode() == Instruction::GetElementPtr)
589 return cast<User>(V);
590 return false;
591}
592
Dan Gohmaneee962e2008-04-10 18:43:06 +0000593/// getOpcode - If this is an Instruction or a ConstantExpr, return the
594/// opcode value. Otherwise return UserOp1.
595static unsigned getOpcode(User *U) {
596 if (Instruction *I = dyn_cast<Instruction>(U))
597 return I->getOpcode();
598 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
599 return CE->getOpcode();
600 // Use UserOp1 to mean there's no opcode.
601 return Instruction::UserOp1;
602}
603
Reid Spencer7177c3a2007-03-25 05:33:51 +0000604/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000605static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000606 APInt Val(C->getValue());
607 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000608}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000609/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000610static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000611 APInt Val(C->getValue());
612 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000613}
614/// Add - Add two ConstantInts together
615static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
616 return ConstantInt::get(C1->getValue() + C2->getValue());
617}
618/// And - Bitwise AND two ConstantInts together
619static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
620 return ConstantInt::get(C1->getValue() & C2->getValue());
621}
622/// Subtract - Subtract one ConstantInt from another
623static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
624 return ConstantInt::get(C1->getValue() - C2->getValue());
625}
626/// Multiply - Multiply two ConstantInts together
627static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
628 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000629}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000630/// MultiplyOverflows - True if the multiply can not be expressed in an int
631/// this size.
632static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
633 uint32_t W = C1->getBitWidth();
634 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
635 if (sign) {
636 LHSExt.sext(W * 2);
637 RHSExt.sext(W * 2);
638 } else {
639 LHSExt.zext(W * 2);
640 RHSExt.zext(W * 2);
641 }
642
643 APInt MulExt = LHSExt * RHSExt;
644
645 if (sign) {
646 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
647 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
648 return MulExt.slt(Min) || MulExt.sgt(Max);
649 } else
650 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
651}
Chris Lattner955f3312004-09-28 21:48:02 +0000652
Chris Lattner68d5ff22006-02-09 07:38:58 +0000653/// ComputeMaskedBits - Determine which of the bits specified in Mask are
654/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000655/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
656/// processing.
657/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
658/// we cannot optimize based on the assumption that it is zero without changing
659/// it to be an explicit zero. If we don't change it to zero, other code could
660/// optimized based on the contradictory assumption that it is non-zero.
661/// Because instcombine aggressively folds operations with undef args anyway,
662/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000663void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
664 APInt& KnownZero, APInt& KnownOne,
665 unsigned Depth) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000666 assert(V && "No Value?");
667 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000668 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000669 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
670 "Not integer or pointer type!");
671 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
672 (!isa<IntegerType>(V->getType()) ||
673 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000674 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000675 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000676 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000677 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
678 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000679 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000680 KnownZero = ~KnownOne & Mask;
681 return;
682 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000683 // Null is all-zeros.
684 if (isa<ConstantPointerNull>(V)) {
685 KnownOne.clear();
686 KnownZero = Mask;
687 return;
688 }
689 // The address of an aligned GlobalValue has trailing zeros.
690 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
691 unsigned Align = GV->getAlignment();
692 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
693 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
694 if (Align > 0)
695 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
696 CountTrailingZeros_32(Align));
697 else
698 KnownZero.clear();
699 KnownOne.clear();
700 return;
701 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000702
Reid Spencer3e7594f2007-03-08 01:46:38 +0000703 if (Depth == 6 || Mask == 0)
704 return; // Limit search depth.
705
Dan Gohmaneee962e2008-04-10 18:43:06 +0000706 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000707 if (!I) return;
708
Zhou Sheng771dbf72007-03-13 02:23:10 +0000709 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000710 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000711
Dan Gohmaneee962e2008-04-10 18:43:06 +0000712 switch (getOpcode(I)) {
713 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000714 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000715 // If either the LHS or the RHS are Zero, the result is zero.
716 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000717 APInt Mask2(Mask & ~KnownZero);
718 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000719 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
720 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
721
722 // Output known-1 bits are only known if set in both the LHS & RHS.
723 KnownOne &= KnownOne2;
724 // Output known-0 are known to be clear if zero in either the LHS | RHS.
725 KnownZero |= KnownZero2;
726 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000727 }
728 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000729 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000730 APInt Mask2(Mask & ~KnownOne);
731 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000732 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
733 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
734
735 // Output known-0 bits are only known if clear in both the LHS & RHS.
736 KnownZero &= KnownZero2;
737 // Output known-1 are known to be set if set in either the LHS | RHS.
738 KnownOne |= KnownOne2;
739 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000740 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000741 case Instruction::Xor: {
742 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
743 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
744 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
745 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
746
747 // Output known-0 bits are known if clear or set in both the LHS & RHS.
748 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
749 // Output known-1 are known to be set if set in only one of the LHS, RHS.
750 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
751 KnownZero = KnownZeroOut;
752 return;
753 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000754 case Instruction::Mul: {
755 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
756 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
757 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
758 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
759 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
760
761 // If low bits are zero in either operand, output low known-0 bits.
762 // More trickiness is possible, but this is sufficient for the
763 // interesting case of alignment computation.
764 KnownOne.clear();
765 unsigned TrailZ = KnownZero.countTrailingOnes() +
766 KnownZero2.countTrailingOnes();
767 TrailZ = std::min(TrailZ, BitWidth);
768 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
769 KnownZero &= Mask;
770 return;
771 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000772 case Instruction::Select:
773 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
774 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
775 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
776 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
777
778 // Only known if known in both the LHS and RHS.
779 KnownOne &= KnownOne2;
780 KnownZero &= KnownZero2;
781 return;
782 case Instruction::FPTrunc:
783 case Instruction::FPExt:
784 case Instruction::FPToUI:
785 case Instruction::FPToSI:
786 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000787 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000788 return; // Can't work with floating point.
789 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000790 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000791 // We can't handle these if we don't know the pointer size.
792 if (!TD) return;
793 // Fall through and handle them the same as zext/trunc.
794 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000795 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000796 // All these have integer operands
Dan Gohmaneee962e2008-04-10 18:43:06 +0000797 const Type *SrcTy = I->getOperand(0)->getType();
798 uint32_t SrcBitWidth = TD ?
799 TD->getTypeSizeInBits(SrcTy) :
800 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000801 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000802 MaskIn.zextOrTrunc(SrcBitWidth);
803 KnownZero.zextOrTrunc(SrcBitWidth);
804 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000805 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000806 KnownZero.zextOrTrunc(BitWidth);
807 KnownOne.zextOrTrunc(BitWidth);
808 // Any top bits are known to be zero.
809 if (BitWidth > SrcBitWidth)
810 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000811 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000812 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000813 case Instruction::BitCast: {
814 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000815 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000816 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
817 return;
818 }
819 break;
820 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000821 case Instruction::SExt: {
822 // Compute the bits in the result that are not present in the input.
823 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000824 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000825
Zhou Shengaa305ab2007-03-28 02:19:03 +0000826 APInt MaskIn(Mask);
827 MaskIn.trunc(SrcBitWidth);
828 KnownZero.trunc(SrcBitWidth);
829 KnownOne.trunc(SrcBitWidth);
830 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000831 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000832 KnownZero.zext(BitWidth);
833 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000834
835 // If the sign bit of the input is known set or clear, then we know the
836 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000837 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000838 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000839 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000840 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000841 return;
842 }
843 case Instruction::Shl:
844 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
845 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000846 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000847 APInt Mask2(Mask.lshr(ShiftAmt));
848 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000849 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000850 KnownZero <<= ShiftAmt;
851 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000852 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000853 return;
854 }
855 break;
856 case Instruction::LShr:
857 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
858 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
859 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000860 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000861
862 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000863 APInt Mask2(Mask.shl(ShiftAmt));
864 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000865 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
866 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
867 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000868 // high bits known zero.
869 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000870 return;
871 }
872 break;
873 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000874 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000875 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
876 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000877 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000878
879 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000880 APInt Mask2(Mask.shl(ShiftAmt));
881 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000882 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
883 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
884 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
885
Zhou Shengaa305ab2007-03-28 02:19:03 +0000886 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
887 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000888 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000889 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000890 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000891 return;
892 }
893 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000894 case Instruction::Sub: {
895 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
896 // We know that the top bits of C-X are clear if X contains less bits
897 // than C (i.e. no wrap-around can happen). For example, 20-X is
898 // positive if we can prove that X is >= 0 and < 16.
899 if (!CLHS->getValue().isNegative()) {
900 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
901 // NLZ can't be BitWidth with no sign bit
902 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
903 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
904
905 // If all of the MaskV bits are known to be zero, then we know the output
906 // top bits are zero, because we now know that the output is from [0-C].
907 if ((KnownZero & MaskV) == MaskV) {
908 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
909 // Top bits known zero.
910 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
911 KnownOne = APInt(BitWidth, 0); // No one bits known.
912 } else {
913 KnownZero = KnownOne = APInt(BitWidth, 0); // Otherwise, nothing known.
914 }
915 return;
916 }
917 }
918 }
919 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000920 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000921 // If either the LHS or the RHS are Zero, the result is zero.
922 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
923 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
924 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
925 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
926
927 // Output known-0 bits are known if clear or set in both the low clear bits
928 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
929 // low 3 bits clear.
930 unsigned KnownZeroOut = std::min(KnownZero.countTrailingOnes(),
931 KnownZero2.countTrailingOnes());
932
933 KnownZero = APInt::getLowBitsSet(BitWidth, KnownZeroOut);
934 KnownOne = APInt(BitWidth, 0);
935 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000936 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000937 case Instruction::SRem:
938 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
939 APInt RA = Rem->getValue();
940 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
941 APInt LowBits = RA.isStrictlyPositive() ? ((RA - 1) | RA) : ~RA;
942 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
943 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
944
945 // The sign of a remainder is equal to the sign of the first
946 // operand (zero being positive).
947 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
948 KnownZero2 |= ~LowBits;
949 else if (KnownOne2[BitWidth-1])
950 KnownOne2 |= ~LowBits;
951
952 KnownZero |= KnownZero2 & Mask;
953 KnownOne |= KnownOne2 & Mask;
954
955 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
956 }
957 }
958 break;
959 case Instruction::URem:
960 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
961 APInt RA = Rem->getValue();
962 if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
963 APInt LowBits = (RA - 1) | RA;
964 APInt Mask2 = LowBits & Mask;
965 KnownZero |= ~LowBits & Mask;
966 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
967 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
968 }
969 } else {
970 // Since the result is less than or equal to RHS, any leading zero bits
971 // in RHS must also exist in the result.
972 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000973 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
974 Depth+1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000975
976 uint32_t Leaders = KnownZero2.countLeadingOnes();
977 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
978 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
979 }
980 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000981
982 case Instruction::Alloca:
983 case Instruction::Malloc: {
984 AllocationInst *AI = cast<AllocationInst>(V);
985 unsigned Align = AI->getAlignment();
986 if (Align == 0 && TD) {
987 if (isa<AllocaInst>(AI))
988 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
989 else if (isa<MallocInst>(AI)) {
990 // Malloc returns maximally aligned memory.
991 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
992 Align =
993 std::max(Align,
994 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
995 Align =
996 std::max(Align,
997 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
998 }
999 }
1000
1001 if (Align > 0)
1002 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1003 CountTrailingZeros_32(Align));
1004 break;
1005 }
1006 case Instruction::GetElementPtr: {
1007 // Analyze all of the subscripts of this getelementptr instruction
1008 // to determine if we can prove known low zero bits.
1009 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1010 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1011 ComputeMaskedBits(I->getOperand(0), LocalMask,
1012 LocalKnownZero, LocalKnownOne, Depth+1);
1013 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1014
1015 gep_type_iterator GTI = gep_type_begin(I);
1016 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1017 Value *Index = I->getOperand(i);
1018 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1019 // Handle struct member offset arithmetic.
1020 if (!TD) return;
1021 const StructLayout *SL = TD->getStructLayout(STy);
1022 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1023 uint64_t Offset = SL->getElementOffset(Idx);
1024 TrailZ = std::min(TrailZ,
1025 CountTrailingZeros_64(Offset));
1026 } else {
1027 // Handle array index arithmetic.
1028 const Type *IndexedTy = GTI.getIndexedType();
1029 if (!IndexedTy->isSized()) return;
1030 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1031 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1032 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1033 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1034 ComputeMaskedBits(Index, LocalMask,
1035 LocalKnownZero, LocalKnownOne, Depth+1);
1036 TrailZ = std::min(TrailZ,
1037 CountTrailingZeros_64(TypeSize) +
1038 LocalKnownZero.countTrailingOnes());
1039 }
1040 }
1041
1042 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1043 break;
1044 }
1045 case Instruction::PHI: {
1046 PHINode *P = cast<PHINode>(I);
1047 // Handle the case of a simple two-predecessor recurrence PHI.
1048 // There's a lot more that could theoretically be done here, but
1049 // this is sufficient to catch some interesting cases.
1050 if (P->getNumIncomingValues() == 2) {
1051 for (unsigned i = 0; i != 2; ++i) {
1052 Value *L = P->getIncomingValue(i);
1053 Value *R = P->getIncomingValue(!i);
1054 User *LU = dyn_cast<User>(L);
1055 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1056 // Check for operations that have the property that if
1057 // both their operands have low zero bits, the result
1058 // will have low zero bits.
1059 if (Opcode == Instruction::Add ||
1060 Opcode == Instruction::Sub ||
1061 Opcode == Instruction::And ||
1062 Opcode == Instruction::Or ||
1063 Opcode == Instruction::Mul) {
1064 Value *LL = LU->getOperand(0);
1065 Value *LR = LU->getOperand(1);
1066 // Find a recurrence.
1067 if (LL == I)
1068 L = LR;
1069 else if (LR == I)
1070 L = LL;
1071 else
1072 break;
1073 // Ok, we have a PHI of the form L op= R. Check for low
1074 // zero bits.
1075 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1076 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1077 Mask2 = APInt::getLowBitsSet(BitWidth,
1078 KnownZero2.countTrailingOnes());
1079 KnownOne2.clear();
1080 KnownZero2.clear();
1081 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1082 KnownZero = Mask &
1083 APInt::getLowBitsSet(BitWidth,
1084 KnownZero2.countTrailingOnes());
1085 break;
1086 }
1087 }
1088 }
1089 break;
1090 }
Reid Spencer3e7594f2007-03-08 01:46:38 +00001091 }
1092}
1093
Reid Spencere7816b52007-03-08 01:52:58 +00001094/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1095/// this predicate to simplify operations downstream. Mask is known to be zero
1096/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001097bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1098 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001099 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001100 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1101 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1102 return (KnownZero & Mask) == Mask;
1103}
1104
Chris Lattner255d8912006-02-11 09:31:47 +00001105/// ShrinkDemandedConstant - Check to see if the specified operand of the
1106/// specified instruction is a constant integer. If so, check to see if there
1107/// are any bits set in the constant that are not demanded. If so, shrink the
1108/// constant and return true.
1109static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001110 APInt Demanded) {
1111 assert(I && "No instruction?");
1112 assert(OpNo < I->getNumOperands() && "Operand index too large");
1113
1114 // If the operand is not a constant integer, nothing to do.
1115 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1116 if (!OpC) return false;
1117
1118 // If there are no bits set that aren't demanded, nothing to do.
1119 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1120 if ((~Demanded & OpC->getValue()) == 0)
1121 return false;
1122
1123 // This instruction is producing bits that are not demanded. Shrink the RHS.
1124 Demanded &= OpC->getValue();
1125 I->setOperand(OpNo, ConstantInt::get(Demanded));
1126 return true;
1127}
1128
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001129// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1130// set of known zero and one bits, compute the maximum and minimum values that
1131// could have the specified known zero and known one bits, returning them in
1132// min/max.
1133static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001134 const APInt& KnownZero,
1135 const APInt& KnownOne,
1136 APInt& Min, APInt& Max) {
1137 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1138 assert(KnownZero.getBitWidth() == BitWidth &&
1139 KnownOne.getBitWidth() == BitWidth &&
1140 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1141 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001142 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001143
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001144 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1145 // bit if it is unknown.
1146 Min = KnownOne;
1147 Max = KnownOne|UnknownBits;
1148
Zhou Sheng4acf1552007-03-28 05:15:57 +00001149 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001150 Min.set(BitWidth-1);
1151 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001152 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001153}
1154
1155// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1156// a set of known zero and one bits, compute the maximum and minimum values that
1157// could have the specified known zero and known one bits, returning them in
1158// min/max.
1159static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001160 const APInt &KnownZero,
1161 const APInt &KnownOne,
1162 APInt &Min, APInt &Max) {
1163 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001164 assert(KnownZero.getBitWidth() == BitWidth &&
1165 KnownOne.getBitWidth() == BitWidth &&
1166 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1167 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001168 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001169
1170 // The minimum value is when the unknown bits are all zeros.
1171 Min = KnownOne;
1172 // The maximum value is when the unknown bits are all ones.
1173 Max = KnownOne|UnknownBits;
1174}
Chris Lattner255d8912006-02-11 09:31:47 +00001175
Reid Spencer8cb68342007-03-12 17:25:59 +00001176/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1177/// value based on the demanded bits. When this function is called, it is known
1178/// that only the bits set in DemandedMask of the result of V are ever used
1179/// downstream. Consequently, depending on the mask and V, it may be possible
1180/// to replace V with a constant or one of its operands. In such cases, this
1181/// function does the replacement and returns true. In all other cases, it
1182/// returns false after analyzing the expression and setting KnownOne and known
1183/// to be one in the expression. KnownZero contains all the bits that are known
1184/// to be zero in the expression. These are provided to potentially allow the
1185/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1186/// the expression. KnownOne and KnownZero always follow the invariant that
1187/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1188/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1189/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1190/// and KnownOne must all be the same.
1191bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1192 APInt& KnownZero, APInt& KnownOne,
1193 unsigned Depth) {
1194 assert(V != 0 && "Null pointer of Value???");
1195 assert(Depth <= 6 && "Limit Search Depth");
1196 uint32_t BitWidth = DemandedMask.getBitWidth();
1197 const IntegerType *VTy = cast<IntegerType>(V->getType());
1198 assert(VTy->getBitWidth() == BitWidth &&
1199 KnownZero.getBitWidth() == BitWidth &&
1200 KnownOne.getBitWidth() == BitWidth &&
1201 "Value *V, DemandedMask, KnownZero and KnownOne \
1202 must have same BitWidth");
1203 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1204 // We know all of the bits for a constant!
1205 KnownOne = CI->getValue() & DemandedMask;
1206 KnownZero = ~KnownOne & DemandedMask;
1207 return false;
1208 }
1209
Zhou Sheng96704452007-03-14 03:21:24 +00001210 KnownZero.clear();
1211 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001212 if (!V->hasOneUse()) { // Other users may use these bits.
1213 if (Depth != 0) { // Not at the root.
1214 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1215 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1216 return false;
1217 }
1218 // If this is the root being simplified, allow it to have multiple uses,
1219 // just set the DemandedMask to all bits.
1220 DemandedMask = APInt::getAllOnesValue(BitWidth);
1221 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1222 if (V != UndefValue::get(VTy))
1223 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1224 return false;
1225 } else if (Depth == 6) { // Limit search depth.
1226 return false;
1227 }
1228
1229 Instruction *I = dyn_cast<Instruction>(V);
1230 if (!I) return false; // Only analyze instructions.
1231
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1233 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1234 switch (I->getOpcode()) {
1235 default: break;
1236 case Instruction::And:
1237 // If either the LHS or the RHS are Zero, the result is zero.
1238 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1239 RHSKnownZero, RHSKnownOne, Depth+1))
1240 return true;
1241 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1242 "Bits known to be one AND zero?");
1243
1244 // If something is known zero on the RHS, the bits aren't demanded on the
1245 // LHS.
1246 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1247 LHSKnownZero, LHSKnownOne, Depth+1))
1248 return true;
1249 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1250 "Bits known to be one AND zero?");
1251
1252 // If all of the demanded bits are known 1 on one side, return the other.
1253 // These bits cannot contribute to the result of the 'and'.
1254 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1255 (DemandedMask & ~LHSKnownZero))
1256 return UpdateValueUsesWith(I, I->getOperand(0));
1257 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1258 (DemandedMask & ~RHSKnownZero))
1259 return UpdateValueUsesWith(I, I->getOperand(1));
1260
1261 // If all of the demanded bits in the inputs are known zeros, return zero.
1262 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1263 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1264
1265 // If the RHS is a constant, see if we can simplify it.
1266 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1267 return UpdateValueUsesWith(I, I);
1268
1269 // Output known-1 bits are only known if set in both the LHS & RHS.
1270 RHSKnownOne &= LHSKnownOne;
1271 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1272 RHSKnownZero |= LHSKnownZero;
1273 break;
1274 case Instruction::Or:
1275 // If either the LHS or the RHS are One, the result is One.
1276 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1277 RHSKnownZero, RHSKnownOne, Depth+1))
1278 return true;
1279 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1280 "Bits known to be one AND zero?");
1281 // If something is known one on the RHS, the bits aren't demanded on the
1282 // LHS.
1283 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1284 LHSKnownZero, LHSKnownOne, Depth+1))
1285 return true;
1286 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1287 "Bits known to be one AND zero?");
1288
1289 // If all of the demanded bits are known zero on one side, return the other.
1290 // These bits cannot contribute to the result of the 'or'.
1291 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1292 (DemandedMask & ~LHSKnownOne))
1293 return UpdateValueUsesWith(I, I->getOperand(0));
1294 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1295 (DemandedMask & ~RHSKnownOne))
1296 return UpdateValueUsesWith(I, I->getOperand(1));
1297
1298 // If all of the potentially set bits on one side are known to be set on
1299 // the other side, just use the 'other' side.
1300 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1301 (DemandedMask & (~RHSKnownZero)))
1302 return UpdateValueUsesWith(I, I->getOperand(0));
1303 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1304 (DemandedMask & (~LHSKnownZero)))
1305 return UpdateValueUsesWith(I, I->getOperand(1));
1306
1307 // If the RHS is a constant, see if we can simplify it.
1308 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1309 return UpdateValueUsesWith(I, I);
1310
1311 // Output known-0 bits are only known if clear in both the LHS & RHS.
1312 RHSKnownZero &= LHSKnownZero;
1313 // Output known-1 are known to be set if set in either the LHS | RHS.
1314 RHSKnownOne |= LHSKnownOne;
1315 break;
1316 case Instruction::Xor: {
1317 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1318 RHSKnownZero, RHSKnownOne, Depth+1))
1319 return true;
1320 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1321 "Bits known to be one AND zero?");
1322 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1323 LHSKnownZero, LHSKnownOne, Depth+1))
1324 return true;
1325 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1326 "Bits known to be one AND zero?");
1327
1328 // If all of the demanded bits are known zero on one side, return the other.
1329 // These bits cannot contribute to the result of the 'xor'.
1330 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1331 return UpdateValueUsesWith(I, I->getOperand(0));
1332 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1333 return UpdateValueUsesWith(I, I->getOperand(1));
1334
1335 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1336 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1337 (RHSKnownOne & LHSKnownOne);
1338 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1339 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1340 (RHSKnownOne & LHSKnownZero);
1341
1342 // If all of the demanded bits are known to be zero on one side or the
1343 // other, turn this into an *inclusive* or.
1344 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1345 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1346 Instruction *Or =
1347 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1348 I->getName());
1349 InsertNewInstBefore(Or, *I);
1350 return UpdateValueUsesWith(I, Or);
1351 }
1352
1353 // If all of the demanded bits on one side are known, and all of the set
1354 // bits on that side are also known to be set on the other side, turn this
1355 // into an AND, as we know the bits will be cleared.
1356 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1357 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1358 // all known
1359 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1360 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1361 Instruction *And =
1362 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1363 InsertNewInstBefore(And, *I);
1364 return UpdateValueUsesWith(I, And);
1365 }
1366 }
1367
1368 // If the RHS is a constant, see if we can simplify it.
1369 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1370 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1371 return UpdateValueUsesWith(I, I);
1372
1373 RHSKnownZero = KnownZeroOut;
1374 RHSKnownOne = KnownOneOut;
1375 break;
1376 }
1377 case Instruction::Select:
1378 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1379 RHSKnownZero, RHSKnownOne, Depth+1))
1380 return true;
1381 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1382 LHSKnownZero, LHSKnownOne, Depth+1))
1383 return true;
1384 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1385 "Bits known to be one AND zero?");
1386 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1387 "Bits known to be one AND zero?");
1388
1389 // If the operands are constants, see if we can simplify them.
1390 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1391 return UpdateValueUsesWith(I, I);
1392 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1393 return UpdateValueUsesWith(I, I);
1394
1395 // Only known if known in both the LHS and RHS.
1396 RHSKnownOne &= LHSKnownOne;
1397 RHSKnownZero &= LHSKnownZero;
1398 break;
1399 case Instruction::Trunc: {
1400 uint32_t truncBf =
1401 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001402 DemandedMask.zext(truncBf);
1403 RHSKnownZero.zext(truncBf);
1404 RHSKnownOne.zext(truncBf);
1405 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1406 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001407 return true;
1408 DemandedMask.trunc(BitWidth);
1409 RHSKnownZero.trunc(BitWidth);
1410 RHSKnownOne.trunc(BitWidth);
1411 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1412 "Bits known to be one AND zero?");
1413 break;
1414 }
1415 case Instruction::BitCast:
1416 if (!I->getOperand(0)->getType()->isInteger())
1417 return false;
1418
1419 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1420 RHSKnownZero, RHSKnownOne, Depth+1))
1421 return true;
1422 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1423 "Bits known to be one AND zero?");
1424 break;
1425 case Instruction::ZExt: {
1426 // Compute the bits in the result that are not present in the input.
1427 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001428 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001429
Zhou Shengd48653a2007-03-29 04:45:55 +00001430 DemandedMask.trunc(SrcBitWidth);
1431 RHSKnownZero.trunc(SrcBitWidth);
1432 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001433 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1434 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001435 return true;
1436 DemandedMask.zext(BitWidth);
1437 RHSKnownZero.zext(BitWidth);
1438 RHSKnownOne.zext(BitWidth);
1439 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1440 "Bits known to be one AND zero?");
1441 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001442 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001443 break;
1444 }
1445 case Instruction::SExt: {
1446 // Compute the bits in the result that are not present in the input.
1447 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001448 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001449
Reid Spencer8cb68342007-03-12 17:25:59 +00001450 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001451 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001452
Zhou Sheng01542f32007-03-29 02:26:30 +00001453 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001454 // If any of the sign extended bits are demanded, we know that the sign
1455 // bit is demanded.
1456 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001457 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001458
Zhou Shengd48653a2007-03-29 04:45:55 +00001459 InputDemandedBits.trunc(SrcBitWidth);
1460 RHSKnownZero.trunc(SrcBitWidth);
1461 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001462 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1463 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001464 return true;
1465 InputDemandedBits.zext(BitWidth);
1466 RHSKnownZero.zext(BitWidth);
1467 RHSKnownOne.zext(BitWidth);
1468 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1469 "Bits known to be one AND zero?");
1470
1471 // If the sign bit of the input is known set or clear, then we know the
1472 // top bits of the result.
1473
1474 // If the input sign bit is known zero, or if the NewBits are not demanded
1475 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001476 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001477 {
1478 // Convert to ZExt cast
1479 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1480 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001481 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001482 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001483 }
1484 break;
1485 }
1486 case Instruction::Add: {
1487 // Figure out what the input bits are. If the top bits of the and result
1488 // are not demanded, then the add doesn't demand them from its input
1489 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001490 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001491
1492 // If there is a constant on the RHS, there are a variety of xformations
1493 // we can do.
1494 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1495 // If null, this should be simplified elsewhere. Some of the xforms here
1496 // won't work if the RHS is zero.
1497 if (RHS->isZero())
1498 break;
1499
1500 // If the top bit of the output is demanded, demand everything from the
1501 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001502 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001503
1504 // Find information about known zero/one bits in the input.
1505 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1506 LHSKnownZero, LHSKnownOne, Depth+1))
1507 return true;
1508
1509 // If the RHS of the add has bits set that can't affect the input, reduce
1510 // the constant.
1511 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1512 return UpdateValueUsesWith(I, I);
1513
1514 // Avoid excess work.
1515 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1516 break;
1517
1518 // Turn it into OR if input bits are zero.
1519 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1520 Instruction *Or =
1521 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1522 I->getName());
1523 InsertNewInstBefore(Or, *I);
1524 return UpdateValueUsesWith(I, Or);
1525 }
1526
1527 // We can say something about the output known-zero and known-one bits,
1528 // depending on potential carries from the input constant and the
1529 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1530 // bits set and the RHS constant is 0x01001, then we know we have a known
1531 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1532
1533 // To compute this, we first compute the potential carry bits. These are
1534 // the bits which may be modified. I'm not aware of a better way to do
1535 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001536 const APInt& RHSVal = RHS->getValue();
1537 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001538
1539 // Now that we know which bits have carries, compute the known-1/0 sets.
1540
1541 // Bits are known one if they are known zero in one operand and one in the
1542 // other, and there is no input carry.
1543 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1544 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1545
1546 // Bits are known zero if they are known zero in both operands and there
1547 // is no input carry.
1548 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1549 } else {
1550 // If the high-bits of this ADD are not demanded, then it does not demand
1551 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001552 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001553 // Right fill the mask of bits for this ADD to demand the most
1554 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001555 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001556 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1557 LHSKnownZero, LHSKnownOne, Depth+1))
1558 return true;
1559 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1560 LHSKnownZero, LHSKnownOne, Depth+1))
1561 return true;
1562 }
1563 }
1564 break;
1565 }
1566 case Instruction::Sub:
1567 // If the high-bits of this SUB are not demanded, then it does not demand
1568 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001569 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001570 // Right fill the mask of bits for this SUB to demand the most
1571 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001572 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001573 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001574 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1575 LHSKnownZero, LHSKnownOne, Depth+1))
1576 return true;
1577 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1578 LHSKnownZero, LHSKnownOne, Depth+1))
1579 return true;
1580 }
1581 break;
1582 case Instruction::Shl:
1583 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001584 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001585 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1586 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001587 RHSKnownZero, RHSKnownOne, Depth+1))
1588 return true;
1589 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1590 "Bits known to be one AND zero?");
1591 RHSKnownZero <<= ShiftAmt;
1592 RHSKnownOne <<= ShiftAmt;
1593 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001594 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001595 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001596 }
1597 break;
1598 case Instruction::LShr:
1599 // For a logical shift right
1600 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001601 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001602
Reid Spencer8cb68342007-03-12 17:25:59 +00001603 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001604 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1605 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001606 RHSKnownZero, RHSKnownOne, Depth+1))
1607 return true;
1608 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1609 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001610 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1611 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001612 if (ShiftAmt) {
1613 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001614 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001615 RHSKnownZero |= HighBits; // high bits known zero.
1616 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001617 }
1618 break;
1619 case Instruction::AShr:
1620 // If this is an arithmetic shift right and only the low-bit is set, we can
1621 // always convert this into a logical shr, even if the shift amount is
1622 // variable. The low bit of the shift cannot be an input sign bit unless
1623 // the shift amount is >= the size of the datatype, which is undefined.
1624 if (DemandedMask == 1) {
1625 // Perform the logical shift right.
1626 Value *NewVal = BinaryOperator::createLShr(
1627 I->getOperand(0), I->getOperand(1), I->getName());
1628 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1629 return UpdateValueUsesWith(I, NewVal);
1630 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001631
1632 // If the sign bit is the only bit demanded by this ashr, then there is no
1633 // need to do it, the shift doesn't change the high bit.
1634 if (DemandedMask.isSignBit())
1635 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001636
1637 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001638 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001639
Reid Spencer8cb68342007-03-12 17:25:59 +00001640 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001641 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001642 // If any of the "high bits" are demanded, we should set the sign bit as
1643 // demanded.
1644 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1645 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001646 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001647 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001648 RHSKnownZero, RHSKnownOne, Depth+1))
1649 return true;
1650 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1651 "Bits known to be one AND zero?");
1652 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001653 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001654 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1655 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1656
1657 // Handle the sign bits.
1658 APInt SignBit(APInt::getSignBit(BitWidth));
1659 // Adjust to where it is now in the mask.
1660 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1661
1662 // If the input sign bit is known to be zero, or if none of the top bits
1663 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001664 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001665 (HighBits & ~DemandedMask) == HighBits) {
1666 // Perform the logical shift right.
1667 Value *NewVal = BinaryOperator::createLShr(
1668 I->getOperand(0), SA, I->getName());
1669 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1670 return UpdateValueUsesWith(I, NewVal);
1671 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1672 RHSKnownOne |= HighBits;
1673 }
1674 }
1675 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001676 case Instruction::SRem:
1677 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1678 APInt RA = Rem->getValue();
1679 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1680 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) | RA : ~RA;
1681 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1682 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1683 LHSKnownZero, LHSKnownOne, Depth+1))
1684 return true;
1685
1686 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1687 LHSKnownZero |= ~LowBits;
1688 else if (LHSKnownOne[BitWidth-1])
1689 LHSKnownOne |= ~LowBits;
1690
1691 KnownZero |= LHSKnownZero & DemandedMask;
1692 KnownOne |= LHSKnownOne & DemandedMask;
1693
1694 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1695 }
1696 }
1697 break;
1698 case Instruction::URem:
1699 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1700 APInt RA = Rem->getValue();
1701 if (RA.isPowerOf2()) {
1702 APInt LowBits = (RA - 1) | RA;
1703 APInt Mask2 = LowBits & DemandedMask;
1704 KnownZero |= ~LowBits & DemandedMask;
1705 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1706 KnownZero, KnownOne, Depth+1))
1707 return true;
1708
1709 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1710 }
1711 } else {
1712 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1713 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1714 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1715 KnownZero2, KnownOne2, Depth+1))
1716 return true;
1717
1718 uint32_t Leaders = KnownZero2.countLeadingOnes();
1719 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1720 }
1721 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001722 }
1723
1724 // If the client is only demanding bits that we know, return the known
1725 // constant.
1726 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1727 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1728 return false;
1729}
1730
Chris Lattner867b99f2006-10-05 06:55:50 +00001731
1732/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1733/// 64 or fewer elements. DemandedElts contains the set of elements that are
1734/// actually used by the caller. This method analyzes which elements of the
1735/// operand are undef and returns that information in UndefElts.
1736///
1737/// If the information about demanded elements can be used to simplify the
1738/// operation, the operation is simplified, then the resultant value is
1739/// returned. This returns null if no change was made.
1740Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1741 uint64_t &UndefElts,
1742 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001743 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001744 assert(VWidth <= 64 && "Vector too wide to analyze!");
1745 uint64_t EltMask = ~0ULL >> (64-VWidth);
1746 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1747 "Invalid DemandedElts!");
1748
1749 if (isa<UndefValue>(V)) {
1750 // If the entire vector is undefined, just return this info.
1751 UndefElts = EltMask;
1752 return 0;
1753 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1754 UndefElts = EltMask;
1755 return UndefValue::get(V->getType());
1756 }
1757
1758 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001759 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1760 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001761 Constant *Undef = UndefValue::get(EltTy);
1762
1763 std::vector<Constant*> Elts;
1764 for (unsigned i = 0; i != VWidth; ++i)
1765 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1766 Elts.push_back(Undef);
1767 UndefElts |= (1ULL << i);
1768 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1769 Elts.push_back(Undef);
1770 UndefElts |= (1ULL << i);
1771 } else { // Otherwise, defined.
1772 Elts.push_back(CP->getOperand(i));
1773 }
1774
1775 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001776 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001777 return NewCP != CP ? NewCP : 0;
1778 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001779 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001780 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001781 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001782 Constant *Zero = Constant::getNullValue(EltTy);
1783 Constant *Undef = UndefValue::get(EltTy);
1784 std::vector<Constant*> Elts;
1785 for (unsigned i = 0; i != VWidth; ++i)
1786 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1787 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001788 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001789 }
1790
1791 if (!V->hasOneUse()) { // Other users may use these bits.
1792 if (Depth != 0) { // Not at the root.
1793 // TODO: Just compute the UndefElts information recursively.
1794 return false;
1795 }
1796 return false;
1797 } else if (Depth == 10) { // Limit search depth.
1798 return false;
1799 }
1800
1801 Instruction *I = dyn_cast<Instruction>(V);
1802 if (!I) return false; // Only analyze instructions.
1803
1804 bool MadeChange = false;
1805 uint64_t UndefElts2;
1806 Value *TmpV;
1807 switch (I->getOpcode()) {
1808 default: break;
1809
1810 case Instruction::InsertElement: {
1811 // If this is a variable index, we don't know which element it overwrites.
1812 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001813 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001814 if (Idx == 0) {
1815 // Note that we can't propagate undef elt info, because we don't know
1816 // which elt is getting updated.
1817 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1818 UndefElts2, Depth+1);
1819 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1820 break;
1821 }
1822
1823 // If this is inserting an element that isn't demanded, remove this
1824 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001825 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001826 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1827 return AddSoonDeadInstToWorklist(*I, 0);
1828
1829 // Otherwise, the element inserted overwrites whatever was there, so the
1830 // input demanded set is simpler than the output set.
1831 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1832 DemandedElts & ~(1ULL << IdxNo),
1833 UndefElts, Depth+1);
1834 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1835
1836 // The inserted element is defined.
1837 UndefElts |= 1ULL << IdxNo;
1838 break;
1839 }
Chris Lattner69878332007-04-14 22:29:23 +00001840 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001841 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001842 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1843 if (!VTy) break;
1844 unsigned InVWidth = VTy->getNumElements();
1845 uint64_t InputDemandedElts = 0;
1846 unsigned Ratio;
1847
1848 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001849 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001850 // elements as are demanded of us.
1851 Ratio = 1;
1852 InputDemandedElts = DemandedElts;
1853 } else if (VWidth > InVWidth) {
1854 // Untested so far.
1855 break;
1856
1857 // If there are more elements in the result than there are in the source,
1858 // then an input element is live if any of the corresponding output
1859 // elements are live.
1860 Ratio = VWidth/InVWidth;
1861 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1862 if (DemandedElts & (1ULL << OutIdx))
1863 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1864 }
1865 } else {
1866 // Untested so far.
1867 break;
1868
1869 // If there are more elements in the source than there are in the result,
1870 // then an input element is live if the corresponding output element is
1871 // live.
1872 Ratio = InVWidth/VWidth;
1873 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1874 if (DemandedElts & (1ULL << InIdx/Ratio))
1875 InputDemandedElts |= 1ULL << InIdx;
1876 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001877
Chris Lattner69878332007-04-14 22:29:23 +00001878 // div/rem demand all inputs, because they don't want divide by zero.
1879 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1880 UndefElts2, Depth+1);
1881 if (TmpV) {
1882 I->setOperand(0, TmpV);
1883 MadeChange = true;
1884 }
1885
1886 UndefElts = UndefElts2;
1887 if (VWidth > InVWidth) {
1888 assert(0 && "Unimp");
1889 // If there are more elements in the result than there are in the source,
1890 // then an output element is undef if the corresponding input element is
1891 // undef.
1892 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1893 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1894 UndefElts |= 1ULL << OutIdx;
1895 } else if (VWidth < InVWidth) {
1896 assert(0 && "Unimp");
1897 // If there are more elements in the source than there are in the result,
1898 // then a result element is undef if all of the corresponding input
1899 // elements are undef.
1900 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1901 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1902 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1903 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1904 }
1905 break;
1906 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001907 case Instruction::And:
1908 case Instruction::Or:
1909 case Instruction::Xor:
1910 case Instruction::Add:
1911 case Instruction::Sub:
1912 case Instruction::Mul:
1913 // div/rem demand all inputs, because they don't want divide by zero.
1914 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1915 UndefElts, Depth+1);
1916 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1917 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1918 UndefElts2, Depth+1);
1919 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1920
1921 // Output elements are undefined if both are undefined. Consider things
1922 // like undef&0. The result is known zero, not undef.
1923 UndefElts &= UndefElts2;
1924 break;
1925
1926 case Instruction::Call: {
1927 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1928 if (!II) break;
1929 switch (II->getIntrinsicID()) {
1930 default: break;
1931
1932 // Binary vector operations that work column-wise. A dest element is a
1933 // function of the corresponding input elements from the two inputs.
1934 case Intrinsic::x86_sse_sub_ss:
1935 case Intrinsic::x86_sse_mul_ss:
1936 case Intrinsic::x86_sse_min_ss:
1937 case Intrinsic::x86_sse_max_ss:
1938 case Intrinsic::x86_sse2_sub_sd:
1939 case Intrinsic::x86_sse2_mul_sd:
1940 case Intrinsic::x86_sse2_min_sd:
1941 case Intrinsic::x86_sse2_max_sd:
1942 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1943 UndefElts, Depth+1);
1944 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1945 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1946 UndefElts2, Depth+1);
1947 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1948
1949 // If only the low elt is demanded and this is a scalarizable intrinsic,
1950 // scalarize it now.
1951 if (DemandedElts == 1) {
1952 switch (II->getIntrinsicID()) {
1953 default: break;
1954 case Intrinsic::x86_sse_sub_ss:
1955 case Intrinsic::x86_sse_mul_ss:
1956 case Intrinsic::x86_sse2_sub_sd:
1957 case Intrinsic::x86_sse2_mul_sd:
1958 // TODO: Lower MIN/MAX/ABS/etc
1959 Value *LHS = II->getOperand(1);
1960 Value *RHS = II->getOperand(2);
1961 // Extract the element as scalars.
1962 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1963 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1964
1965 switch (II->getIntrinsicID()) {
1966 default: assert(0 && "Case stmts out of sync!");
1967 case Intrinsic::x86_sse_sub_ss:
1968 case Intrinsic::x86_sse2_sub_sd:
1969 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1970 II->getName()), *II);
1971 break;
1972 case Intrinsic::x86_sse_mul_ss:
1973 case Intrinsic::x86_sse2_mul_sd:
1974 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1975 II->getName()), *II);
1976 break;
1977 }
1978
1979 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001980 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1981 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001982 InsertNewInstBefore(New, *II);
1983 AddSoonDeadInstToWorklist(*II, 0);
1984 return New;
1985 }
1986 }
1987
1988 // Output elements are undefined if both are undefined. Consider things
1989 // like undef&0. The result is known zero, not undef.
1990 UndefElts &= UndefElts2;
1991 break;
1992 }
1993 break;
1994 }
1995 }
1996 return MadeChange ? I : 0;
1997}
1998
Nick Lewycky455e1762007-09-06 02:40:25 +00001999/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00002000/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00002001/// @brief Determine if the icmp Predicate is true when both operands are equal
2002static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002003 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
2004 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2005 pred == ICmpInst::ICMP_SLE;
2006}
2007
Nick Lewycky455e1762007-09-06 02:40:25 +00002008/// @returns true if the specified compare instruction is
2009/// true when both operands are equal...
2010/// @brief Determine if the ICmpInst returns true when both operands are equal
2011static bool isTrueWhenEqual(ICmpInst &ICI) {
2012 return isTrueWhenEqual(ICI.getPredicate());
2013}
2014
Chris Lattner564a7272003-08-13 19:01:45 +00002015/// AssociativeOpt - Perform an optimization on an associative operator. This
2016/// function is designed to check a chain of associative operators for a
2017/// potential to apply a certain optimization. Since the optimization may be
2018/// applicable if the expression was reassociated, this checks the chain, then
2019/// reassociates the expression as necessary to expose the optimization
2020/// opportunity. This makes use of a special Functor, which must define
2021/// 'shouldApply' and 'apply' methods.
2022///
2023template<typename Functor>
2024Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2025 unsigned Opcode = Root.getOpcode();
2026 Value *LHS = Root.getOperand(0);
2027
2028 // Quick check, see if the immediate LHS matches...
2029 if (F.shouldApply(LHS))
2030 return F.apply(Root);
2031
2032 // Otherwise, if the LHS is not of the same opcode as the root, return.
2033 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002034 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002035 // Should we apply this transform to the RHS?
2036 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2037
2038 // If not to the RHS, check to see if we should apply to the LHS...
2039 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2040 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2041 ShouldApply = true;
2042 }
2043
2044 // If the functor wants to apply the optimization to the RHS of LHSI,
2045 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2046 if (ShouldApply) {
2047 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002048
Chris Lattner564a7272003-08-13 19:01:45 +00002049 // Now all of the instructions are in the current basic block, go ahead
2050 // and perform the reassociation.
2051 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2052
2053 // First move the selected RHS to the LHS of the root...
2054 Root.setOperand(0, LHSI->getOperand(1));
2055
2056 // Make what used to be the LHS of the root be the user of the root...
2057 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002058 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002059 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2060 return 0;
2061 }
Chris Lattner65725312004-04-16 18:08:07 +00002062 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002063 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002064 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2065 BasicBlock::iterator ARI = &Root; ++ARI;
2066 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2067 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002068
2069 // Now propagate the ExtraOperand down the chain of instructions until we
2070 // get to LHSI.
2071 while (TmpLHSI != LHSI) {
2072 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002073 // Move the instruction to immediately before the chain we are
2074 // constructing to avoid breaking dominance properties.
2075 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2076 BB->getInstList().insert(ARI, NextLHSI);
2077 ARI = NextLHSI;
2078
Chris Lattner564a7272003-08-13 19:01:45 +00002079 Value *NextOp = NextLHSI->getOperand(1);
2080 NextLHSI->setOperand(1, ExtraOperand);
2081 TmpLHSI = NextLHSI;
2082 ExtraOperand = NextOp;
2083 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002084
Chris Lattner564a7272003-08-13 19:01:45 +00002085 // Now that the instructions are reassociated, have the functor perform
2086 // the transformation...
2087 return F.apply(Root);
2088 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002089
Chris Lattner564a7272003-08-13 19:01:45 +00002090 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2091 }
2092 return 0;
2093}
2094
2095
2096// AddRHS - Implements: X + X --> X << 1
2097struct AddRHS {
2098 Value *RHS;
2099 AddRHS(Value *rhs) : RHS(rhs) {}
2100 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2101 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00002102 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00002103 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002104 }
2105};
2106
2107// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2108// iff C1&C2 == 0
2109struct AddMaskingAnd {
2110 Constant *C2;
2111 AddMaskingAnd(Constant *c) : C2(c) {}
2112 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002113 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002114 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002115 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002116 }
2117 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00002118 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002119 }
2120};
2121
Chris Lattner6e7ba452005-01-01 16:22:27 +00002122static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002123 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002124 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002125 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002126 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002127
Reid Spencer3da59db2006-11-27 01:05:10 +00002128 return IC->InsertNewInstBefore(CastInst::create(
2129 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002130 }
2131
Chris Lattner2eefe512004-04-09 19:05:30 +00002132 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002133 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2134 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002135
Chris Lattner2eefe512004-04-09 19:05:30 +00002136 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2137 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002138 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2139 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002140 }
2141
2142 Value *Op0 = SO, *Op1 = ConstOperand;
2143 if (!ConstIsRHS)
2144 std::swap(Op0, Op1);
2145 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002146 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2147 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002148 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2149 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
2150 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002151 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002152 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002153 abort();
2154 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002155 return IC->InsertNewInstBefore(New, I);
2156}
2157
2158// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2159// constant as the other operand, try to fold the binary operator into the
2160// select arguments. This also works for Cast instructions, which obviously do
2161// not have a second operand.
2162static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2163 InstCombiner *IC) {
2164 // Don't modify shared select instructions
2165 if (!SI->hasOneUse()) return 0;
2166 Value *TV = SI->getOperand(1);
2167 Value *FV = SI->getOperand(2);
2168
2169 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002170 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002171 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002172
Chris Lattner6e7ba452005-01-01 16:22:27 +00002173 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2174 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2175
Gabor Greif051a9502008-04-06 20:25:17 +00002176 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2177 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002178 }
2179 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002180}
2181
Chris Lattner4e998b22004-09-29 05:07:12 +00002182
2183/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2184/// node as operand #0, see if we can fold the instruction into the PHI (which
2185/// is only possible if all operands to the PHI are constants).
2186Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2187 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002188 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002189 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002190
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002191 // Check to see if all of the operands of the PHI are constants. If there is
2192 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002193 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002194 BasicBlock *NonConstBB = 0;
2195 for (unsigned i = 0; i != NumPHIValues; ++i)
2196 if (!isa<Constant>(PN->getIncomingValue(i))) {
2197 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002198 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002199 NonConstBB = PN->getIncomingBlock(i);
2200
2201 // If the incoming non-constant value is in I's block, we have an infinite
2202 // loop.
2203 if (NonConstBB == I.getParent())
2204 return 0;
2205 }
2206
2207 // If there is exactly one non-constant value, we can insert a copy of the
2208 // operation in that block. However, if this is a critical edge, we would be
2209 // inserting the computation one some other paths (e.g. inside a loop). Only
2210 // do this if the pred block is unconditionally branching into the phi block.
2211 if (NonConstBB) {
2212 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2213 if (!BI || !BI->isUnconditional()) return 0;
2214 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002215
2216 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002217 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002218 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002219 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002220 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002221
2222 // Next, add all of the operands to the PHI.
2223 if (I.getNumOperands() == 2) {
2224 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002225 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002226 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002227 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002228 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2229 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2230 else
2231 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002232 } else {
2233 assert(PN->getIncomingBlock(i) == NonConstBB);
2234 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2235 InV = BinaryOperator::create(BO->getOpcode(),
2236 PN->getIncomingValue(i), C, "phitmp",
2237 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002238 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2239 InV = CmpInst::create(CI->getOpcode(),
2240 CI->getPredicate(),
2241 PN->getIncomingValue(i), C, "phitmp",
2242 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002243 else
2244 assert(0 && "Unknown binop!");
2245
Chris Lattnerdbab3862007-03-02 21:28:56 +00002246 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002247 }
2248 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002249 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002250 } else {
2251 CastInst *CI = cast<CastInst>(&I);
2252 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002253 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002254 Value *InV;
2255 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002256 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002257 } else {
2258 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00002259 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2260 I.getType(), "phitmp",
2261 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002262 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002263 }
2264 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002265 }
2266 }
2267 return ReplaceInstUsesWith(I, NewPN);
2268}
2269
Chris Lattner2454a2e2008-01-29 06:52:45 +00002270
2271/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2272/// value is never equal to -0.0.
2273///
2274/// Note that this function will need to be revisited when we support nondefault
2275/// rounding modes!
2276///
2277static bool CannotBeNegativeZero(const Value *V) {
2278 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2279 return !CFP->getValueAPF().isNegZero();
2280
2281 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2282 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2283 if (I->getOpcode() == Instruction::Add &&
2284 isa<ConstantFP>(I->getOperand(1)) &&
2285 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2286 return true;
2287
2288 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2289 if (II->getIntrinsicID() == Intrinsic::sqrt)
2290 return CannotBeNegativeZero(II->getOperand(1));
2291
2292 if (const CallInst *CI = dyn_cast<CallInst>(I))
2293 if (const Function *F = CI->getCalledFunction()) {
2294 if (F->isDeclaration()) {
2295 switch (F->getNameLen()) {
2296 case 3: // abs(x) != -0.0
2297 if (!strcmp(F->getNameStart(), "abs")) return true;
2298 break;
2299 case 4: // abs[lf](x) != -0.0
2300 if (!strcmp(F->getNameStart(), "absf")) return true;
2301 if (!strcmp(F->getNameStart(), "absl")) return true;
2302 break;
2303 }
2304 }
2305 }
2306 }
2307
2308 return false;
2309}
2310
2311
Chris Lattner7e708292002-06-25 16:13:24 +00002312Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002313 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002314 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002315
Chris Lattner66331a42004-04-10 22:01:55 +00002316 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002317 // X + undef -> undef
2318 if (isa<UndefValue>(RHS))
2319 return ReplaceInstUsesWith(I, RHS);
2320
Chris Lattner66331a42004-04-10 22:01:55 +00002321 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002322 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002323 if (RHSC->isNullValue())
2324 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002325 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002326 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2327 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002328 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002329 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002330
Chris Lattner66331a42004-04-10 22:01:55 +00002331 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002332 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002333 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002334 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002335 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00002336 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002337
2338 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2339 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002340 if (!isa<VectorType>(I.getType())) {
2341 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2342 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2343 KnownZero, KnownOne))
2344 return &I;
2345 }
Chris Lattner66331a42004-04-10 22:01:55 +00002346 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002347
2348 if (isa<PHINode>(LHS))
2349 if (Instruction *NV = FoldOpIntoPhi(I))
2350 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002351
Chris Lattner4f637d42006-01-06 17:59:59 +00002352 ConstantInt *XorRHS = 0;
2353 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002354 if (isa<ConstantInt>(RHSC) &&
2355 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002356 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002357 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002358
Zhou Sheng4351c642007-04-02 08:20:41 +00002359 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002360 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2361 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002362 do {
2363 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002364 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2365 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002366 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2367 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002368 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002369 if (!MaskedValueIsZero(XorLHS,
2370 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002371 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002372 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002373 }
2374 }
2375 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002376 C0080Val = APIntOps::lshr(C0080Val, Size);
2377 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2378 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002379
Reid Spencer35c38852007-03-28 01:36:16 +00002380 // FIXME: This shouldn't be necessary. When the backends can handle types
2381 // with funny bit widths then this whole cascade of if statements should
2382 // be removed. It is just here to get the size of the "middle" type back
2383 // up to something that the back ends can handle.
2384 const Type *MiddleType = 0;
2385 switch (Size) {
2386 default: break;
2387 case 32: MiddleType = Type::Int32Ty; break;
2388 case 16: MiddleType = Type::Int16Ty; break;
2389 case 8: MiddleType = Type::Int8Ty; break;
2390 }
2391 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002392 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002393 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002394 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002395 }
2396 }
Chris Lattner66331a42004-04-10 22:01:55 +00002397 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002398
Chris Lattner564a7272003-08-13 19:01:45 +00002399 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002400 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002401 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002402
2403 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2404 if (RHSI->getOpcode() == Instruction::Sub)
2405 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2406 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2407 }
2408 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2409 if (LHSI->getOpcode() == Instruction::Sub)
2410 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2411 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2412 }
Robert Bocchino71698282004-07-27 21:02:21 +00002413 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002414
Chris Lattner5c4afb92002-05-08 22:46:53 +00002415 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002416 // -A + -B --> -(A + B)
2417 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002418 if (LHS->getType()->isIntOrIntVector()) {
2419 if (Value *RHSV = dyn_castNegVal(RHS)) {
2420 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2421 InsertNewInstBefore(NewAdd, I);
2422 return BinaryOperator::createNeg(NewAdd);
2423 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002424 }
2425
2426 return BinaryOperator::createSub(RHS, LHSV);
2427 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002428
2429 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002430 if (!isa<Constant>(RHS))
2431 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002432 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002433
Misha Brukmanfd939082005-04-21 23:48:37 +00002434
Chris Lattner50af16a2004-11-13 19:50:12 +00002435 ConstantInt *C2;
2436 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2437 if (X == RHS) // X*C + X --> X * (C+1)
2438 return BinaryOperator::createMul(RHS, AddOne(C2));
2439
2440 // X*C1 + X*C2 --> X * (C1+C2)
2441 ConstantInt *C1;
2442 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002443 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002444 }
2445
2446 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002447 if (dyn_castFoldableMul(RHS, C2) == LHS)
2448 return BinaryOperator::createMul(LHS, AddOne(C2));
2449
Chris Lattnere617c9e2007-01-05 02:17:46 +00002450 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002451 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2452 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002453
Chris Lattnerad3448c2003-02-18 19:57:07 +00002454
Chris Lattner564a7272003-08-13 19:01:45 +00002455 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002456 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002457 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2458 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002459
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002460 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002461 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002462 Value *W, *X, *Y, *Z;
2463 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2464 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2465 if (W != Y) {
2466 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002467 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002468 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002469 std::swap(W, X);
2470 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002471 std::swap(Y, Z);
2472 std::swap(W, X);
2473 }
2474 }
2475
2476 if (W == Y) {
2477 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2478 LHS->getName()), I);
2479 return BinaryOperator::createMul(W, NewAdd);
2480 }
2481 }
2482 }
2483
Chris Lattner6b032052003-10-02 15:11:26 +00002484 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002485 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002486 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2487 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002488
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002489 // (X & FF00) + xx00 -> (X+xx00) & FF00
2490 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002491 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002492 if (Anded == CRHS) {
2493 // See if all bits from the first bit set in the Add RHS up are included
2494 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002495 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002496
2497 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002498 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002499
2500 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002501 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002502
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002503 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2504 // Okay, the xform is safe. Insert the new add pronto.
2505 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2506 LHS->getName()), I);
2507 return BinaryOperator::createAnd(NewAdd, C2);
2508 }
2509 }
2510 }
2511
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002512 // Try to fold constant add into select arguments.
2513 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002514 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002515 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002516 }
2517
Reid Spencer1628cec2006-10-26 06:15:43 +00002518 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002519 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002520 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002521 CastInst *CI = dyn_cast<CastInst>(LHS);
2522 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002523 if (!CI) {
2524 CI = dyn_cast<CastInst>(RHS);
2525 Other = LHS;
2526 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002527 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002528 (CI->getType()->getPrimitiveSizeInBits() ==
2529 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002530 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002531 unsigned AS =
2532 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002533 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2534 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002535 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002536 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002537 }
2538 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002539
Chris Lattner42790482007-12-20 01:56:58 +00002540 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002541 {
2542 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2543 Value *Other = RHS;
2544 if (!SI) {
2545 SI = dyn_cast<SelectInst>(RHS);
2546 Other = LHS;
2547 }
Chris Lattner42790482007-12-20 01:56:58 +00002548 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002549 Value *TV = SI->getTrueValue();
2550 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002551 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002552
2553 // Can we fold the add into the argument of the select?
2554 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002555 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2556 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002557 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002558 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2559 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002560 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002561 }
2562 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002563
2564 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2565 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2566 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2567 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002568
Chris Lattner7e708292002-06-25 16:13:24 +00002569 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002570}
2571
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002572// isSignBit - Return true if the value represented by the constant only has the
2573// highest order bit set.
2574static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002575 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002576 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002577}
2578
Chris Lattner7e708292002-06-25 16:13:24 +00002579Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002580 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002581
Chris Lattner233f7dc2002-08-12 21:17:25 +00002582 if (Op0 == Op1) // sub X, X -> 0
2583 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002584
Chris Lattner233f7dc2002-08-12 21:17:25 +00002585 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002586 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002587 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002588
Chris Lattnere87597f2004-10-16 18:11:37 +00002589 if (isa<UndefValue>(Op0))
2590 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2591 if (isa<UndefValue>(Op1))
2592 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2593
Chris Lattnerd65460f2003-11-05 01:06:05 +00002594 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2595 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002596 if (C->isAllOnesValue())
2597 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002598
Chris Lattnerd65460f2003-11-05 01:06:05 +00002599 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002600 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002601 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002602 return BinaryOperator::createAdd(X, AddOne(C));
2603
Chris Lattner76b7a062007-01-15 07:02:54 +00002604 // -(X >>u 31) -> (X >>s 31)
2605 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002606 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002607 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002608 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002609 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002610 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002611 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002612 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002613 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002614 return BinaryOperator::create(Instruction::AShr,
2615 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002616 }
2617 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002618 }
2619 else if (SI->getOpcode() == Instruction::AShr) {
2620 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2621 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002622 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002623 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002624 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002625 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002626 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002627 }
2628 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002629 }
2630 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002631 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002632
2633 // Try to fold constant sub into select arguments.
2634 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002635 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002636 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002637
2638 if (isa<PHINode>(Op0))
2639 if (Instruction *NV = FoldOpIntoPhi(I))
2640 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002641 }
2642
Chris Lattner43d84d62005-04-07 16:15:25 +00002643 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2644 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002645 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002646 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002647 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002648 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002649 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002650 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2651 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2652 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002653 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002654 Op1I->getOperand(0));
2655 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002656 }
2657
Chris Lattnerfd059242003-10-15 16:48:29 +00002658 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002659 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2660 // is not used by anyone else...
2661 //
Chris Lattner0517e722004-02-02 20:09:56 +00002662 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002663 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002664 // Swap the two operands of the subexpr...
2665 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2666 Op1I->setOperand(0, IIOp1);
2667 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002668
Chris Lattnera2881962003-02-18 19:28:33 +00002669 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002670 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002671 }
2672
2673 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2674 //
2675 if (Op1I->getOpcode() == Instruction::And &&
2676 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2677 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2678
Chris Lattnerf523d062004-06-09 05:08:07 +00002679 Value *NewNot =
2680 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002681 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002682 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002683
Reid Spencerac5209e2006-10-16 23:08:08 +00002684 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002685 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002686 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002687 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002688 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002689 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002690 ConstantExpr::getNeg(DivRHS));
2691
Chris Lattnerad3448c2003-02-18 19:57:07 +00002692 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002693 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002694 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002695 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002696 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002697 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002698
2699 // X - ((X / Y) * Y) --> X % Y
2700 if (Op1I->getOpcode() == Instruction::Mul)
2701 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2702 if (Op0 == I->getOperand(0) &&
2703 Op1I->getOperand(1) == I->getOperand(1)) {
2704 if (I->getOpcode() == Instruction::SDiv)
2705 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2706 if (I->getOpcode() == Instruction::UDiv)
2707 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2708 }
Chris Lattner40371712002-05-09 01:29:19 +00002709 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002710 }
Chris Lattnera2881962003-02-18 19:28:33 +00002711
Chris Lattner9919e3d2006-12-02 00:13:08 +00002712 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002713 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002714 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002715 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2716 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2717 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2718 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002719 } else if (Op0I->getOpcode() == Instruction::Sub) {
2720 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2721 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002722 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002723 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002724
Chris Lattner50af16a2004-11-13 19:50:12 +00002725 ConstantInt *C1;
2726 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002727 if (X == Op1) // X*C - X --> X * (C-1)
2728 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002729
Chris Lattner50af16a2004-11-13 19:50:12 +00002730 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2731 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Sheng58d13af2008-02-22 10:00:35 +00002732 return BinaryOperator::createMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002733 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002734 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002735}
2736
Chris Lattnera0141b92007-07-15 20:42:37 +00002737/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2738/// comparison only checks the sign bit. If it only checks the sign bit, set
2739/// TrueIfSigned if the result of the comparison is true when the input value is
2740/// signed.
2741static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2742 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002743 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002744 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2745 TrueIfSigned = true;
2746 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002747 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2748 TrueIfSigned = true;
2749 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002750 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2751 TrueIfSigned = false;
2752 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002753 case ICmpInst::ICMP_UGT:
2754 // True if LHS u> RHS and RHS == high-bit-mask - 1
2755 TrueIfSigned = true;
2756 return RHS->getValue() ==
2757 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2758 case ICmpInst::ICMP_UGE:
2759 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2760 TrueIfSigned = true;
2761 return RHS->getValue() ==
2762 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002763 default:
2764 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002765 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002766}
2767
Chris Lattner7e708292002-06-25 16:13:24 +00002768Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002769 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002770 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002771
Chris Lattnere87597f2004-10-16 18:11:37 +00002772 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2773 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2774
Chris Lattner233f7dc2002-08-12 21:17:25 +00002775 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002776 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2777 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002778
2779 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002780 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002781 if (SI->getOpcode() == Instruction::Shl)
2782 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002783 return BinaryOperator::createMul(SI->getOperand(0),
2784 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002785
Zhou Sheng843f07672007-04-19 05:39:12 +00002786 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002787 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2788 if (CI->equalsInt(1)) // X * 1 == X
2789 return ReplaceInstUsesWith(I, Op0);
2790 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002791 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002792
Zhou Sheng97b52c22007-03-29 01:57:21 +00002793 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002794 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002795 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002796 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002797 }
Robert Bocchino71698282004-07-27 21:02:21 +00002798 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002799 if (Op1F->isNullValue())
2800 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002801
Chris Lattnera2881962003-02-18 19:28:33 +00002802 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2803 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002804 // We need a better interface for long double here.
2805 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2806 if (Op1F->isExactlyValue(1.0))
2807 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002808 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002809
2810 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2811 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2812 isa<ConstantInt>(Op0I->getOperand(1))) {
2813 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2814 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2815 Op1, "tmp");
2816 InsertNewInstBefore(Add, I);
2817 Value *C1C2 = ConstantExpr::getMul(Op1,
2818 cast<Constant>(Op0I->getOperand(1)));
2819 return BinaryOperator::createAdd(Add, C1C2);
2820
2821 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002822
2823 // Try to fold constant mul into select arguments.
2824 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002825 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002826 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002827
2828 if (isa<PHINode>(Op0))
2829 if (Instruction *NV = FoldOpIntoPhi(I))
2830 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002831 }
2832
Chris Lattnera4f445b2003-03-10 23:23:04 +00002833 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2834 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002835 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002836
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002837 // If one of the operands of the multiply is a cast from a boolean value, then
2838 // we know the bool is either zero or one, so this is a 'masking' multiply.
2839 // See if we can simplify things based on how the boolean was originally
2840 // formed.
2841 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002842 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002843 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002844 BoolCast = CI;
2845 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002846 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002847 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002848 BoolCast = CI;
2849 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002850 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002851 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2852 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002853 bool TIS = false;
2854
Reid Spencere4d87aa2006-12-23 06:05:41 +00002855 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002856 // multiply into a shift/and combination.
2857 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002858 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2859 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002860 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002861 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002862 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002863 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002864 InsertNewInstBefore(
2865 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002866 BoolCast->getOperand(0)->getName()+
2867 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002868
2869 // If the multiply type is not the same as the source type, sign extend
2870 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002871 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002872 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2873 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002874 Instruction::CastOps opcode =
2875 (SrcBits == DstBits ? Instruction::BitCast :
2876 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2877 V = InsertCastBefore(opcode, V, I.getType(), I);
2878 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002879
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002880 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002881 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002882 }
2883 }
2884 }
2885
Chris Lattner7e708292002-06-25 16:13:24 +00002886 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002887}
2888
Reid Spencer1628cec2006-10-26 06:15:43 +00002889/// This function implements the transforms on div instructions that work
2890/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2891/// used by the visitors to those instructions.
2892/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002893Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002894 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002895
Chris Lattner50b2ca42008-02-19 06:12:18 +00002896 // undef / X -> 0 for integer.
2897 // undef / X -> undef for FP (the undef could be a snan).
2898 if (isa<UndefValue>(Op0)) {
2899 if (Op0->getType()->isFPOrFPVector())
2900 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002901 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002902 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002903
2904 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002905 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002906 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002907
Chris Lattner25feae52008-01-28 00:58:18 +00002908 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2909 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002910 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002911 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2912 // the same basic block, then we replace the select with Y, and the
2913 // condition of the select with false (if the cond value is in the same BB).
2914 // If the select has uses other than the div, this allows them to be
2915 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2916 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002917 if (ST->isNullValue()) {
2918 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2919 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002920 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002921 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2922 I.setOperand(1, SI->getOperand(2));
2923 else
2924 UpdateValueUsesWith(SI, SI->getOperand(2));
2925 return &I;
2926 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002927
Chris Lattner25feae52008-01-28 00:58:18 +00002928 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2929 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002930 if (ST->isNullValue()) {
2931 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2932 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002933 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002934 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2935 I.setOperand(1, SI->getOperand(1));
2936 else
2937 UpdateValueUsesWith(SI, SI->getOperand(1));
2938 return &I;
2939 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002940 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002941
Reid Spencer1628cec2006-10-26 06:15:43 +00002942 return 0;
2943}
Misha Brukmanfd939082005-04-21 23:48:37 +00002944
Reid Spencer1628cec2006-10-26 06:15:43 +00002945/// This function implements the transforms common to both integer division
2946/// instructions (udiv and sdiv). It is called by the visitors to those integer
2947/// division instructions.
2948/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002949Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002950 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2951
2952 if (Instruction *Common = commonDivTransforms(I))
2953 return Common;
2954
2955 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2956 // div X, 1 == X
2957 if (RHS->equalsInt(1))
2958 return ReplaceInstUsesWith(I, Op0);
2959
2960 // (X / C1) / C2 -> X / (C1*C2)
2961 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2962 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2963 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002964 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2965 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2966 else
2967 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2968 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002969 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002970
Reid Spencerbca0e382007-03-23 20:05:17 +00002971 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002972 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2973 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2974 return R;
2975 if (isa<PHINode>(Op0))
2976 if (Instruction *NV = FoldOpIntoPhi(I))
2977 return NV;
2978 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002979 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002980
Chris Lattnera2881962003-02-18 19:28:33 +00002981 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002982 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002983 if (LHS->equalsInt(0))
2984 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2985
Reid Spencer1628cec2006-10-26 06:15:43 +00002986 return 0;
2987}
2988
2989Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2990 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2991
2992 // Handle the integer div common cases
2993 if (Instruction *Common = commonIDivTransforms(I))
2994 return Common;
2995
2996 // X udiv C^2 -> X >> C
2997 // Check to see if this is an unsigned division with an exact power of 2,
2998 // if so, convert to a right shift.
2999 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003000 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00003001 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003002 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003003 }
3004
3005 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003006 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003007 if (RHSI->getOpcode() == Instruction::Shl &&
3008 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003009 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003010 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003011 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003012 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003013 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003014 Constant *C2V = ConstantInt::get(NTy, C2);
3015 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003016 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00003017 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003018 }
3019 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003020 }
3021
Reid Spencer1628cec2006-10-26 06:15:43 +00003022 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3023 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003024 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003025 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003026 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003027 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003028 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003029 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003030 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003031 // Construct the "on true" case of the select
3032 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3033 Instruction *TSI = BinaryOperator::createLShr(
3034 Op0, TC, SI->getName()+".t");
3035 TSI = InsertNewInstBefore(TSI, I);
3036
3037 // Construct the "on false" case of the select
3038 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3039 Instruction *FSI = BinaryOperator::createLShr(
3040 Op0, FC, SI->getName()+".f");
3041 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003042
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003043 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003044 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003045 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003046 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003047 return 0;
3048}
3049
Reid Spencer1628cec2006-10-26 06:15:43 +00003050Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3051 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3052
3053 // Handle the integer div common cases
3054 if (Instruction *Common = commonIDivTransforms(I))
3055 return Common;
3056
3057 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3058 // sdiv X, -1 == -X
3059 if (RHS->isAllOnesValue())
3060 return BinaryOperator::createNeg(Op0);
3061
3062 // -X/C -> X/-C
3063 if (Value *LHSNeg = dyn_castNegVal(Op0))
3064 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3065 }
3066
3067 // If the sign bits of both operands are zero (i.e. we can prove they are
3068 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003069 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003070 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003071 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003072 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00003073 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3074 }
3075 }
3076
3077 return 0;
3078}
3079
3080Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3081 return commonDivTransforms(I);
3082}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003083
Reid Spencer0a783f72006-11-02 01:53:59 +00003084/// This function implements the transforms on rem instructions that work
3085/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3086/// is used by the visitors to those instructions.
3087/// @brief Transforms common to all three rem instructions
3088Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003089 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003090
Chris Lattner50b2ca42008-02-19 06:12:18 +00003091 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003092 if (Constant *LHS = dyn_cast<Constant>(Op0))
3093 if (LHS->isNullValue())
3094 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3095
Chris Lattner50b2ca42008-02-19 06:12:18 +00003096 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3097 if (I.getType()->isFPOrFPVector())
3098 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003099 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003100 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003101 if (isa<UndefValue>(Op1))
3102 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003103
3104 // Handle cases involving: rem X, (select Cond, Y, Z)
3105 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3106 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3107 // the same basic block, then we replace the select with Y, and the
3108 // condition of the select with false (if the cond value is in the same
3109 // BB). If the select has uses other than the div, this allows them to be
3110 // simplified also.
3111 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3112 if (ST->isNullValue()) {
3113 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3114 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003115 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003116 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3117 I.setOperand(1, SI->getOperand(2));
3118 else
3119 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003120 return &I;
3121 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003122 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3123 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3124 if (ST->isNullValue()) {
3125 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3126 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003127 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003128 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3129 I.setOperand(1, SI->getOperand(1));
3130 else
3131 UpdateValueUsesWith(SI, SI->getOperand(1));
3132 return &I;
3133 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003134 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003135
Reid Spencer0a783f72006-11-02 01:53:59 +00003136 return 0;
3137}
3138
3139/// This function implements the transforms common to both integer remainder
3140/// instructions (urem and srem). It is called by the visitors to those integer
3141/// remainder instructions.
3142/// @brief Common integer remainder transforms
3143Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3144 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3145
3146 if (Instruction *common = commonRemTransforms(I))
3147 return common;
3148
Chris Lattner857e8cd2004-12-12 21:48:58 +00003149 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003150 // X % 0 == undef, we don't need to preserve faults!
3151 if (RHS->equalsInt(0))
3152 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3153
Chris Lattnera2881962003-02-18 19:28:33 +00003154 if (RHS->equalsInt(1)) // X % 1 == 0
3155 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3156
Chris Lattner97943922006-02-28 05:49:21 +00003157 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3158 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3159 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3160 return R;
3161 } else if (isa<PHINode>(Op0I)) {
3162 if (Instruction *NV = FoldOpIntoPhi(I))
3163 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003164 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003165
3166 // See if we can fold away this rem instruction.
3167 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3168 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3169 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3170 KnownZero, KnownOne))
3171 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003172 }
Chris Lattnera2881962003-02-18 19:28:33 +00003173 }
3174
Reid Spencer0a783f72006-11-02 01:53:59 +00003175 return 0;
3176}
3177
3178Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3179 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3180
3181 if (Instruction *common = commonIRemTransforms(I))
3182 return common;
3183
3184 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3185 // X urem C^2 -> X and C
3186 // Check to see if this is an unsigned remainder with an exact power of 2,
3187 // if so, convert to a bitwise and.
3188 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003189 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00003190 return BinaryOperator::createAnd(Op0, SubOne(C));
3191 }
3192
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003193 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003194 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3195 if (RHSI->getOpcode() == Instruction::Shl &&
3196 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003197 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003198 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3199 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3200 "tmp"), I);
3201 return BinaryOperator::createAnd(Op0, Add);
3202 }
3203 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003204 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003205
Reid Spencer0a783f72006-11-02 01:53:59 +00003206 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3207 // where C1&C2 are powers of two.
3208 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3209 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3210 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3211 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003212 if ((STO->getValue().isPowerOf2()) &&
3213 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003214 Value *TrueAnd = InsertNewInstBefore(
3215 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3216 Value *FalseAnd = InsertNewInstBefore(
3217 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003218 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003219 }
3220 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003221 }
3222
Chris Lattner3f5b8772002-05-06 16:14:14 +00003223 return 0;
3224}
3225
Reid Spencer0a783f72006-11-02 01:53:59 +00003226Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3227 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3228
Dan Gohmancff55092007-11-05 23:16:33 +00003229 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003230 if (Instruction *common = commonIRemTransforms(I))
3231 return common;
3232
3233 if (Value *RHSNeg = dyn_castNegVal(Op1))
3234 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003235 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003236 // X % -Y -> X % Y
3237 AddUsesToWorkList(I);
3238 I.setOperand(1, RHSNeg);
3239 return &I;
3240 }
3241
Dan Gohmancff55092007-11-05 23:16:33 +00003242 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003243 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003244 if (I.getType()->isInteger()) {
3245 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3246 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3247 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3248 return BinaryOperator::createURem(Op0, Op1, I.getName());
3249 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003250 }
3251
3252 return 0;
3253}
3254
3255Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003256 return commonRemTransforms(I);
3257}
3258
Chris Lattner8b170942002-08-09 23:47:40 +00003259// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003260static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003261 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003262 if (!isSigned)
3263 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3264 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003265}
3266
3267// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003268static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003269 if (!isSigned)
3270 return C->getValue() == 1; // unsigned
3271
3272 // Calculate 1111111111000000000000
3273 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3274 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003275}
3276
Chris Lattner457dd822004-06-09 07:59:58 +00003277// isOneBitSet - Return true if there is exactly one bit set in the specified
3278// constant.
3279static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003280 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003281}
3282
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003283// isHighOnes - Return true if the constant is of the form 1+0+.
3284// This is the same as lowones(~X).
3285static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003286 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003287}
3288
Reid Spencere4d87aa2006-12-23 06:05:41 +00003289/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003290/// are carefully arranged to allow folding of expressions such as:
3291///
3292/// (A < B) | (A > B) --> (A != B)
3293///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003294/// Note that this is only valid if the first and second predicates have the
3295/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003296///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003297/// Three bits are used to represent the condition, as follows:
3298/// 0 A > B
3299/// 1 A == B
3300/// 2 A < B
3301///
3302/// <=> Value Definition
3303/// 000 0 Always false
3304/// 001 1 A > B
3305/// 010 2 A == B
3306/// 011 3 A >= B
3307/// 100 4 A < B
3308/// 101 5 A != B
3309/// 110 6 A <= B
3310/// 111 7 Always true
3311///
3312static unsigned getICmpCode(const ICmpInst *ICI) {
3313 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003314 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003315 case ICmpInst::ICMP_UGT: return 1; // 001
3316 case ICmpInst::ICMP_SGT: return 1; // 001
3317 case ICmpInst::ICMP_EQ: return 2; // 010
3318 case ICmpInst::ICMP_UGE: return 3; // 011
3319 case ICmpInst::ICMP_SGE: return 3; // 011
3320 case ICmpInst::ICMP_ULT: return 4; // 100
3321 case ICmpInst::ICMP_SLT: return 4; // 100
3322 case ICmpInst::ICMP_NE: return 5; // 101
3323 case ICmpInst::ICMP_ULE: return 6; // 110
3324 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003325 // True -> 7
3326 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003327 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003328 return 0;
3329 }
3330}
3331
Reid Spencere4d87aa2006-12-23 06:05:41 +00003332/// getICmpValue - This is the complement of getICmpCode, which turns an
3333/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003334/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003335/// of predicate to use in new icmp instructions.
3336static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3337 switch (code) {
3338 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003339 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003340 case 1:
3341 if (sign)
3342 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3343 else
3344 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3345 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3346 case 3:
3347 if (sign)
3348 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3349 else
3350 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3351 case 4:
3352 if (sign)
3353 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3354 else
3355 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3356 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3357 case 6:
3358 if (sign)
3359 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3360 else
3361 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003362 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003363 }
3364}
3365
Reid Spencere4d87aa2006-12-23 06:05:41 +00003366static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3367 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3368 (ICmpInst::isSignedPredicate(p1) &&
3369 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3370 (ICmpInst::isSignedPredicate(p2) &&
3371 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3372}
3373
3374namespace {
3375// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3376struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003377 InstCombiner &IC;
3378 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003379 ICmpInst::Predicate pred;
3380 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3381 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3382 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003383 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3385 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003386 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3387 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003388 return false;
3389 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003390 Instruction *apply(Instruction &Log) const {
3391 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3392 if (ICI->getOperand(0) != LHS) {
3393 assert(ICI->getOperand(1) == LHS);
3394 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003395 }
3396
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003397 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003398 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003399 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003400 unsigned Code;
3401 switch (Log.getOpcode()) {
3402 case Instruction::And: Code = LHSCode & RHSCode; break;
3403 case Instruction::Or: Code = LHSCode | RHSCode; break;
3404 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003405 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003406 }
3407
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003408 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3409 ICmpInst::isSignedPredicate(ICI->getPredicate());
3410
3411 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003412 if (Instruction *I = dyn_cast<Instruction>(RV))
3413 return I;
3414 // Otherwise, it's a constant boolean value...
3415 return IC.ReplaceInstUsesWith(Log, RV);
3416 }
3417};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003418} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003419
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003420// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3421// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003422// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003423Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003424 ConstantInt *OpRHS,
3425 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003426 BinaryOperator &TheAnd) {
3427 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003428 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003429 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003430 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003431
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003432 switch (Op->getOpcode()) {
3433 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003434 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003435 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003436 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003437 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003438 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003439 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003440 }
3441 break;
3442 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003443 if (Together == AndRHS) // (X | C) & C --> C
3444 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003445
Chris Lattner6e7ba452005-01-01 16:22:27 +00003446 if (Op->hasOneUse() && Together != OpRHS) {
3447 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003448 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003449 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003450 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003451 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003452 }
3453 break;
3454 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003455 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003456 // Adding a one to a single bit bit-field should be turned into an XOR
3457 // of the bit. First thing to check is to see if this AND is with a
3458 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003459 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003460
3461 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003462 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003463 // Ok, at this point, we know that we are masking the result of the
3464 // ADD down to exactly one bit. If the constant we are adding has
3465 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003466 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003467
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003468 // Check to see if any bits below the one bit set in AndRHSV are set.
3469 if ((AddRHS & (AndRHSV-1)) == 0) {
3470 // If not, the only thing that can effect the output of the AND is
3471 // the bit specified by AndRHSV. If that bit is set, the effect of
3472 // the XOR is to toggle the bit. If it is clear, then the ADD has
3473 // no effect.
3474 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3475 TheAnd.setOperand(0, X);
3476 return &TheAnd;
3477 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003478 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003479 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003480 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003481 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003482 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003483 }
3484 }
3485 }
3486 }
3487 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003488
3489 case Instruction::Shl: {
3490 // We know that the AND will not produce any of the bits shifted in, so if
3491 // the anded constant includes them, clear them now!
3492 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003493 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003494 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003495 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3496 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003497
Zhou Sheng290bec52007-03-29 08:15:12 +00003498 if (CI->getValue() == ShlMask) {
3499 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003500 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3501 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003502 TheAnd.setOperand(1, CI);
3503 return &TheAnd;
3504 }
3505 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003506 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003507 case Instruction::LShr:
3508 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003509 // We know that the AND will not produce any of the bits shifted in, so if
3510 // the anded constant includes them, clear them now! This only applies to
3511 // unsigned shifts, because a signed shr may bring in set bits!
3512 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003513 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003514 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003515 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3516 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003517
Zhou Sheng290bec52007-03-29 08:15:12 +00003518 if (CI->getValue() == ShrMask) {
3519 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003520 return ReplaceInstUsesWith(TheAnd, Op);
3521 } else if (CI != AndRHS) {
3522 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3523 return &TheAnd;
3524 }
3525 break;
3526 }
3527 case Instruction::AShr:
3528 // Signed shr.
3529 // See if this is shifting in some sign extension, then masking it out
3530 // with an and.
3531 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003532 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003533 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003534 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3535 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003536 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003537 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003538 // Make the argument unsigned.
3539 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003540 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003541 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003542 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003543 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003544 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003545 }
3546 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003547 }
3548 return 0;
3549}
3550
Chris Lattner8b170942002-08-09 23:47:40 +00003551
Chris Lattnera96879a2004-09-29 17:40:11 +00003552/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3553/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003554/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3555/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003556/// insert new instructions.
3557Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003558 bool isSigned, bool Inside,
3559 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003560 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003561 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003562 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003563
Chris Lattnera96879a2004-09-29 17:40:11 +00003564 if (Inside) {
3565 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003566 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003567
Reid Spencere4d87aa2006-12-23 06:05:41 +00003568 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003569 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003570 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003571 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3572 return new ICmpInst(pred, V, Hi);
3573 }
3574
3575 // Emit V-Lo <u Hi-Lo
3576 Constant *NegLo = ConstantExpr::getNeg(Lo);
3577 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003578 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003579 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3580 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003581 }
3582
3583 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003584 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003585
Reid Spencere4e40032007-03-21 23:19:50 +00003586 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003587 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003588 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003589 ICmpInst::Predicate pred = (isSigned ?
3590 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3591 return new ICmpInst(pred, V, Hi);
3592 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003593
Reid Spencere4e40032007-03-21 23:19:50 +00003594 // Emit V-Lo >u Hi-1-Lo
3595 // Note that Hi has already had one subtracted from it, above.
3596 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003597 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003598 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003599 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3600 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003601}
3602
Chris Lattner7203e152005-09-18 07:22:02 +00003603// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3604// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3605// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3606// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003607static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003608 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003609 uint32_t BitWidth = Val->getType()->getBitWidth();
3610 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003611
3612 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003613 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003614 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003615 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003616 return true;
3617}
3618
Chris Lattner7203e152005-09-18 07:22:02 +00003619/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3620/// where isSub determines whether the operator is a sub. If we can fold one of
3621/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003622///
3623/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3624/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3625/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3626///
3627/// return (A +/- B).
3628///
3629Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003630 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003631 Instruction &I) {
3632 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3633 if (!LHSI || LHSI->getNumOperands() != 2 ||
3634 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3635
3636 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3637
3638 switch (LHSI->getOpcode()) {
3639 default: return 0;
3640 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003641 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003642 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003643 if ((Mask->getValue().countLeadingZeros() +
3644 Mask->getValue().countPopulation()) ==
3645 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003646 break;
3647
3648 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3649 // part, we don't need any explicit masks to take them out of A. If that
3650 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003651 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003652 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003653 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003654 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003655 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003656 break;
3657 }
3658 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003659 return 0;
3660 case Instruction::Or:
3661 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003662 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003663 if ((Mask->getValue().countLeadingZeros() +
3664 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003665 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003666 break;
3667 return 0;
3668 }
3669
3670 Instruction *New;
3671 if (isSub)
3672 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3673 else
3674 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3675 return InsertNewInstBefore(New, I);
3676}
3677
Chris Lattner7e708292002-06-25 16:13:24 +00003678Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003679 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003680 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003681
Chris Lattnere87597f2004-10-16 18:11:37 +00003682 if (isa<UndefValue>(Op1)) // X & undef -> 0
3683 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3684
Chris Lattner6e7ba452005-01-01 16:22:27 +00003685 // and X, X = X
3686 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003687 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003688
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003689 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003690 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003691 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003692 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3693 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3694 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003695 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003696 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003697 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003698 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003699 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003700 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003701 } else if (isa<ConstantAggregateZero>(Op1)) {
3702 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003703 }
3704 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003705
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003706 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003707 const APInt& AndRHSMask = AndRHS->getValue();
3708 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003709
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003710 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003711 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003712 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003713 Value *Op0LHS = Op0I->getOperand(0);
3714 Value *Op0RHS = Op0I->getOperand(1);
3715 switch (Op0I->getOpcode()) {
3716 case Instruction::Xor:
3717 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003718 // If the mask is only needed on one incoming arm, push it up.
3719 if (Op0I->hasOneUse()) {
3720 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3721 // Not masking anything out for the LHS, move to RHS.
3722 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3723 Op0RHS->getName()+".masked");
3724 InsertNewInstBefore(NewRHS, I);
3725 return BinaryOperator::create(
3726 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003727 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003728 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003729 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3730 // Not masking anything out for the RHS, move to LHS.
3731 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3732 Op0LHS->getName()+".masked");
3733 InsertNewInstBefore(NewLHS, I);
3734 return BinaryOperator::create(
3735 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3736 }
3737 }
3738
Chris Lattner6e7ba452005-01-01 16:22:27 +00003739 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003740 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003741 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3742 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3743 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3744 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3745 return BinaryOperator::createAnd(V, AndRHS);
3746 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3747 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003748 break;
3749
3750 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003751 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3752 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3753 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3754 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3755 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003756 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003757 }
3758
Chris Lattner58403262003-07-23 19:25:52 +00003759 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003760 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003761 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003762 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003763 // If this is an integer truncation or change from signed-to-unsigned, and
3764 // if the source is an and/or with immediate, transform it. This
3765 // frequently occurs for bitfield accesses.
3766 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003767 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003768 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003769 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003770 if (CastOp->getOpcode() == Instruction::And) {
3771 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003772 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3773 // This will fold the two constants together, which may allow
3774 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003775 Instruction *NewCast = CastInst::createTruncOrBitCast(
3776 CastOp->getOperand(0), I.getType(),
3777 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003778 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003779 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003780 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003781 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003782 return BinaryOperator::createAnd(NewCast, C3);
3783 } else if (CastOp->getOpcode() == Instruction::Or) {
3784 // Change: and (cast (or X, C1) to T), C2
3785 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003786 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003787 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3788 return ReplaceInstUsesWith(I, AndRHS);
3789 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003790 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003791 }
Chris Lattner06782f82003-07-23 19:36:21 +00003792 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003793
3794 // Try to fold constant and into select arguments.
3795 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003796 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003797 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003798 if (isa<PHINode>(Op0))
3799 if (Instruction *NV = FoldOpIntoPhi(I))
3800 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003801 }
3802
Chris Lattner8d969642003-03-10 23:06:50 +00003803 Value *Op0NotVal = dyn_castNotVal(Op0);
3804 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003805
Chris Lattner5b62aa72004-06-18 06:07:51 +00003806 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3807 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3808
Misha Brukmancb6267b2004-07-30 12:50:08 +00003809 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003810 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003811 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3812 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003813 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003814 return BinaryOperator::createNot(Or);
3815 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003816
3817 {
Chris Lattner003b6202007-06-15 05:58:24 +00003818 Value *A = 0, *B = 0, *C = 0, *D = 0;
3819 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003820 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3821 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003822
3823 // (A|B) & ~(A&B) -> A^B
3824 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3825 if ((A == C && B == D) || (A == D && B == C))
3826 return BinaryOperator::createXor(A, B);
3827 }
3828 }
3829
3830 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003831 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3832 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003833
3834 // ~(A&B) & (A|B) -> A^B
3835 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3836 if ((A == C && B == D) || (A == D && B == C))
3837 return BinaryOperator::createXor(A, B);
3838 }
3839 }
Chris Lattner64daab52006-04-01 08:03:55 +00003840
3841 if (Op0->hasOneUse() &&
3842 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3843 if (A == Op1) { // (A^B)&A -> A&(A^B)
3844 I.swapOperands(); // Simplify below
3845 std::swap(Op0, Op1);
3846 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3847 cast<BinaryOperator>(Op0)->swapOperands();
3848 I.swapOperands(); // Simplify below
3849 std::swap(Op0, Op1);
3850 }
3851 }
3852 if (Op1->hasOneUse() &&
3853 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3854 if (B == Op0) { // B&(A^B) -> B&(B^A)
3855 cast<BinaryOperator>(Op1)->swapOperands();
3856 std::swap(A, B);
3857 }
3858 if (A == Op0) { // A&(A^B) -> A & ~B
3859 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3860 InsertNewInstBefore(NotB, I);
3861 return BinaryOperator::createAnd(A, NotB);
3862 }
3863 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003864 }
3865
Reid Spencere4d87aa2006-12-23 06:05:41 +00003866 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3867 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3868 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003869 return R;
3870
Chris Lattner955f3312004-09-28 21:48:02 +00003871 Value *LHSVal, *RHSVal;
3872 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003873 ICmpInst::Predicate LHSCC, RHSCC;
3874 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3875 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3876 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3877 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3878 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3879 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3880 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003881 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3882
3883 // Don't try to fold ICMP_SLT + ICMP_ULT.
3884 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3885 ICmpInst::isSignedPredicate(LHSCC) ==
3886 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003887 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003888 ICmpInst::Predicate GT;
3889 if (ICmpInst::isSignedPredicate(LHSCC) ||
3890 (ICmpInst::isEquality(LHSCC) &&
3891 ICmpInst::isSignedPredicate(RHSCC)))
3892 GT = ICmpInst::ICMP_SGT;
3893 else
3894 GT = ICmpInst::ICMP_UGT;
3895
Reid Spencere4d87aa2006-12-23 06:05:41 +00003896 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3897 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003898 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003899 std::swap(LHS, RHS);
3900 std::swap(LHSCst, RHSCst);
3901 std::swap(LHSCC, RHSCC);
3902 }
3903
Reid Spencere4d87aa2006-12-23 06:05:41 +00003904 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003905 // comparing a value against two constants and and'ing the result
3906 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003907 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3908 // (from the FoldICmpLogical check above), that the two constants
3909 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003910 assert(LHSCst != RHSCst && "Compares not folded above?");
3911
3912 switch (LHSCC) {
3913 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003914 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003915 switch (RHSCC) {
3916 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003917 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3918 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3919 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003920 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003921 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3922 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3923 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003924 return ReplaceInstUsesWith(I, LHS);
3925 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003926 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003927 switch (RHSCC) {
3928 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003929 case ICmpInst::ICMP_ULT:
3930 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3931 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3932 break; // (X != 13 & X u< 15) -> no change
3933 case ICmpInst::ICMP_SLT:
3934 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3935 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3936 break; // (X != 13 & X s< 15) -> no change
3937 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3938 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3939 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003940 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003941 case ICmpInst::ICMP_NE:
3942 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003943 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3944 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3945 LHSVal->getName()+".off");
3946 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003947 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3948 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003949 }
3950 break; // (X != 13 & X != 15) -> no change
3951 }
3952 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003953 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003954 switch (RHSCC) {
3955 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003956 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3957 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003958 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003959 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3960 break;
3961 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3962 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003963 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003964 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3965 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003966 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003967 break;
3968 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003969 switch (RHSCC) {
3970 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003971 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3972 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003973 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003974 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3975 break;
3976 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3977 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003978 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003979 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3980 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003981 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003982 break;
3983 case ICmpInst::ICMP_UGT:
3984 switch (RHSCC) {
3985 default: assert(0 && "Unknown integer condition code!");
3986 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3987 return ReplaceInstUsesWith(I, LHS);
3988 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3989 return ReplaceInstUsesWith(I, RHS);
3990 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3991 break;
3992 case ICmpInst::ICMP_NE:
3993 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3994 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3995 break; // (X u> 13 & X != 15) -> no change
3996 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3997 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3998 true, I);
3999 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4000 break;
4001 }
4002 break;
4003 case ICmpInst::ICMP_SGT:
4004 switch (RHSCC) {
4005 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004006 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004007 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4008 return ReplaceInstUsesWith(I, RHS);
4009 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4010 break;
4011 case ICmpInst::ICMP_NE:
4012 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4013 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4014 break; // (X s> 13 & X != 15) -> no change
4015 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4016 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4017 true, I);
4018 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4019 break;
4020 }
4021 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004022 }
4023 }
4024 }
4025
Chris Lattner6fc205f2006-05-05 06:39:07 +00004026 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004027 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4028 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4029 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4030 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004031 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004032 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004033 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4034 I.getType(), TD) &&
4035 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4036 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004037 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4038 Op1C->getOperand(0),
4039 I.getName());
4040 InsertNewInstBefore(NewOp, I);
4041 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4042 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004043 }
Chris Lattnere511b742006-11-14 07:46:50 +00004044
4045 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004046 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4047 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4048 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004049 SI0->getOperand(1) == SI1->getOperand(1) &&
4050 (SI0->hasOneUse() || SI1->hasOneUse())) {
4051 Instruction *NewOp =
4052 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4053 SI1->getOperand(0),
4054 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004055 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4056 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004057 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004058 }
4059
Chris Lattner99c65742007-10-24 05:38:08 +00004060 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4061 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4062 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4063 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4064 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4065 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4066 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4067 // If either of the constants are nans, then the whole thing returns
4068 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004069 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004070 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4071 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4072 RHS->getOperand(0));
4073 }
4074 }
4075 }
4076
Chris Lattner7e708292002-06-25 16:13:24 +00004077 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004078}
4079
Chris Lattnerafe91a52006-06-15 19:07:26 +00004080/// CollectBSwapParts - Look to see if the specified value defines a single byte
4081/// in the result. If it does, and if the specified byte hasn't been filled in
4082/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004083static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004084 Instruction *I = dyn_cast<Instruction>(V);
4085 if (I == 0) return true;
4086
4087 // If this is an or instruction, it is an inner node of the bswap.
4088 if (I->getOpcode() == Instruction::Or)
4089 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4090 CollectBSwapParts(I->getOperand(1), ByteValues);
4091
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004092 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004093 // If this is a shift by a constant int, and it is "24", then its operand
4094 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004095 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004096 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004097 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004098 8*(ByteValues.size()-1))
4099 return true;
4100
4101 unsigned DestNo;
4102 if (I->getOpcode() == Instruction::Shl) {
4103 // X << 24 defines the top byte with the lowest of the input bytes.
4104 DestNo = ByteValues.size()-1;
4105 } else {
4106 // X >>u 24 defines the low byte with the highest of the input bytes.
4107 DestNo = 0;
4108 }
4109
4110 // If the destination byte value is already defined, the values are or'd
4111 // together, which isn't a bswap (unless it's an or of the same bits).
4112 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4113 return true;
4114 ByteValues[DestNo] = I->getOperand(0);
4115 return false;
4116 }
4117
4118 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4119 // don't have this.
4120 Value *Shift = 0, *ShiftLHS = 0;
4121 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4122 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4123 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4124 return true;
4125 Instruction *SI = cast<Instruction>(Shift);
4126
4127 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004128 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4129 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004130 return true;
4131
4132 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4133 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004134 if (AndAmt->getValue().getActiveBits() > 64)
4135 return true;
4136 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004137 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004138 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004139 break;
4140 // Unknown mask for bswap.
4141 if (DestByte == ByteValues.size()) return true;
4142
Reid Spencerb83eb642006-10-20 07:07:24 +00004143 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004144 unsigned SrcByte;
4145 if (SI->getOpcode() == Instruction::Shl)
4146 SrcByte = DestByte - ShiftBytes;
4147 else
4148 SrcByte = DestByte + ShiftBytes;
4149
4150 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4151 if (SrcByte != ByteValues.size()-DestByte-1)
4152 return true;
4153
4154 // If the destination byte value is already defined, the values are or'd
4155 // together, which isn't a bswap (unless it's an or of the same bits).
4156 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4157 return true;
4158 ByteValues[DestByte] = SI->getOperand(0);
4159 return false;
4160}
4161
4162/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4163/// If so, insert the new bswap intrinsic and return it.
4164Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004165 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4166 if (!ITy || ITy->getBitWidth() % 16)
4167 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004168
4169 /// ByteValues - For each byte of the result, we keep track of which value
4170 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004171 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004172 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004173
4174 // Try to find all the pieces corresponding to the bswap.
4175 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4176 CollectBSwapParts(I.getOperand(1), ByteValues))
4177 return 0;
4178
4179 // Check to see if all of the bytes come from the same value.
4180 Value *V = ByteValues[0];
4181 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4182
4183 // Check to make sure that all of the bytes come from the same value.
4184 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4185 if (ByteValues[i] != V)
4186 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004187 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004188 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004189 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004190 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004191}
4192
4193
Chris Lattner7e708292002-06-25 16:13:24 +00004194Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004195 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004196 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004197
Chris Lattner42593e62007-03-24 23:56:43 +00004198 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004199 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004200
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004201 // or X, X = X
4202 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004203 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004204
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004205 // See if we can simplify any instructions used by the instruction whose sole
4206 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004207 if (!isa<VectorType>(I.getType())) {
4208 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4209 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4210 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4211 KnownZero, KnownOne))
4212 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004213 } else if (isa<ConstantAggregateZero>(Op1)) {
4214 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4215 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4216 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4217 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004218 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004219
4220
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004221
Chris Lattner3f5b8772002-05-06 16:14:14 +00004222 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004223 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004224 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004225 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4226 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004227 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004228 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004229 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004230 return BinaryOperator::createAnd(Or,
4231 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004232 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004233
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004234 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4235 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004236 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004237 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004238 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004239 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004240 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004241 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004242
4243 // Try to fold constant and into select arguments.
4244 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004245 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004246 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004247 if (isa<PHINode>(Op0))
4248 if (Instruction *NV = FoldOpIntoPhi(I))
4249 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004250 }
4251
Chris Lattner4f637d42006-01-06 17:59:59 +00004252 Value *A = 0, *B = 0;
4253 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004254
4255 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4256 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4257 return ReplaceInstUsesWith(I, Op1);
4258 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4259 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4260 return ReplaceInstUsesWith(I, Op0);
4261
Chris Lattner6423d4c2006-07-10 20:25:24 +00004262 // (A | B) | C and A | (B | C) -> bswap if possible.
4263 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004264 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004265 match(Op1, m_Or(m_Value(), m_Value())) ||
4266 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4267 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004268 if (Instruction *BSwap = MatchBSwap(I))
4269 return BSwap;
4270 }
4271
Chris Lattner6e4c6492005-05-09 04:58:36 +00004272 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4273 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004274 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004275 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4276 InsertNewInstBefore(NOr, I);
4277 NOr->takeName(Op0);
4278 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004279 }
4280
4281 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4282 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004283 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004284 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4285 InsertNewInstBefore(NOr, I);
4286 NOr->takeName(Op0);
4287 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004288 }
4289
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004290 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004291 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004292 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4293 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004294 Value *V1 = 0, *V2 = 0, *V3 = 0;
4295 C1 = dyn_cast<ConstantInt>(C);
4296 C2 = dyn_cast<ConstantInt>(D);
4297 if (C1 && C2) { // (A & C1)|(B & C2)
4298 // If we have: ((V + N) & C1) | (V & C2)
4299 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4300 // replace with V+N.
4301 if (C1->getValue() == ~C2->getValue()) {
4302 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4303 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4304 // Add commutes, try both ways.
4305 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4306 return ReplaceInstUsesWith(I, A);
4307 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4308 return ReplaceInstUsesWith(I, A);
4309 }
4310 // Or commutes, try both ways.
4311 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4312 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4313 // Add commutes, try both ways.
4314 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4315 return ReplaceInstUsesWith(I, B);
4316 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4317 return ReplaceInstUsesWith(I, B);
4318 }
4319 }
Chris Lattner044e5332007-04-08 08:01:49 +00004320 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004321 }
4322
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004323 // Check to see if we have any common things being and'ed. If so, find the
4324 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004325 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4326 if (A == B) // (A & C)|(A & D) == A & (C|D)
4327 V1 = A, V2 = C, V3 = D;
4328 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4329 V1 = A, V2 = B, V3 = C;
4330 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4331 V1 = C, V2 = A, V3 = D;
4332 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4333 V1 = C, V2 = A, V3 = B;
4334
4335 if (V1) {
4336 Value *Or =
4337 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4338 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004339 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004340 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004341 }
Chris Lattnere511b742006-11-14 07:46:50 +00004342
4343 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004344 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4345 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4346 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004347 SI0->getOperand(1) == SI1->getOperand(1) &&
4348 (SI0->hasOneUse() || SI1->hasOneUse())) {
4349 Instruction *NewOp =
4350 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4351 SI1->getOperand(0),
4352 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004353 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4354 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004355 }
4356 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004357
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004358 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4359 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004360 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004361 } else {
4362 A = 0;
4363 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004364 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004365 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4366 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004367 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004368
Misha Brukmancb6267b2004-07-30 12:50:08 +00004369 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004370 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4371 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4372 I.getName()+".demorgan"), I);
4373 return BinaryOperator::createNot(And);
4374 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004375 }
Chris Lattnera2881962003-02-18 19:28:33 +00004376
Reid Spencere4d87aa2006-12-23 06:05:41 +00004377 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4378 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4379 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004380 return R;
4381
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004382 Value *LHSVal, *RHSVal;
4383 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004384 ICmpInst::Predicate LHSCC, RHSCC;
4385 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4386 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4387 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4388 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4389 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4390 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4391 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004392 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4393 // We can't fold (ugt x, C) | (sgt x, C2).
4394 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004395 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004396 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004397 bool NeedsSwap;
4398 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004399 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004400 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004401 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004402
4403 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004404 std::swap(LHS, RHS);
4405 std::swap(LHSCst, RHSCst);
4406 std::swap(LHSCC, RHSCC);
4407 }
4408
Reid Spencere4d87aa2006-12-23 06:05:41 +00004409 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004410 // comparing a value against two constants and or'ing the result
4411 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004412 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4413 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004414 // equal.
4415 assert(LHSCst != RHSCst && "Compares not folded above?");
4416
4417 switch (LHSCC) {
4418 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004419 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004420 switch (RHSCC) {
4421 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004422 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004423 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4424 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4425 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4426 LHSVal->getName()+".off");
4427 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004428 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004429 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004430 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004431 break; // (X == 13 | X == 15) -> no change
4432 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4433 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004434 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004435 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4436 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4437 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004438 return ReplaceInstUsesWith(I, RHS);
4439 }
4440 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004441 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004442 switch (RHSCC) {
4443 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004444 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4445 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4446 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004447 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004448 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4449 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4450 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004451 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004452 }
4453 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004454 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004455 switch (RHSCC) {
4456 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004457 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004458 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004459 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004460 // If RHSCst is [us]MAXINT, it is always false. Not handling
4461 // this can cause overflow.
4462 if (RHSCst->isMaxValue(false))
4463 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004464 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4465 false, I);
4466 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4467 break;
4468 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4469 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004470 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004471 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4472 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004473 }
4474 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004475 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004476 switch (RHSCC) {
4477 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004478 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4479 break;
4480 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004481 // If RHSCst is [us]MAXINT, it is always false. Not handling
4482 // this can cause overflow.
4483 if (RHSCst->isMaxValue(true))
4484 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004485 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4486 false, I);
4487 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4488 break;
4489 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4490 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4491 return ReplaceInstUsesWith(I, RHS);
4492 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4493 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004494 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004495 break;
4496 case ICmpInst::ICMP_UGT:
4497 switch (RHSCC) {
4498 default: assert(0 && "Unknown integer condition code!");
4499 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4500 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4501 return ReplaceInstUsesWith(I, LHS);
4502 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4503 break;
4504 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4505 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004506 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004507 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4508 break;
4509 }
4510 break;
4511 case ICmpInst::ICMP_SGT:
4512 switch (RHSCC) {
4513 default: assert(0 && "Unknown integer condition code!");
4514 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4515 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4516 return ReplaceInstUsesWith(I, LHS);
4517 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4518 break;
4519 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4520 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004521 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004522 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4523 break;
4524 }
4525 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004526 }
4527 }
4528 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004529
4530 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004531 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004532 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004533 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004534 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4535 !isa<ICmpInst>(Op1C->getOperand(0))) {
4536 const Type *SrcTy = Op0C->getOperand(0)->getType();
4537 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4538 // Only do this if the casts both really cause code to be
4539 // generated.
4540 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4541 I.getType(), TD) &&
4542 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4543 I.getType(), TD)) {
4544 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4545 Op1C->getOperand(0),
4546 I.getName());
4547 InsertNewInstBefore(NewOp, I);
4548 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4549 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004550 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004551 }
Chris Lattner99c65742007-10-24 05:38:08 +00004552 }
4553
4554
4555 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4556 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4557 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4558 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004559 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4560 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004561 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4562 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4563 // If either of the constants are nans, then the whole thing returns
4564 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004565 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004566 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4567
4568 // Otherwise, no need to compare the two constants, compare the
4569 // rest.
4570 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4571 RHS->getOperand(0));
4572 }
4573 }
4574 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004575
Chris Lattner7e708292002-06-25 16:13:24 +00004576 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004577}
4578
Chris Lattnerc317d392004-02-16 01:20:27 +00004579// XorSelf - Implements: X ^ X --> 0
4580struct XorSelf {
4581 Value *RHS;
4582 XorSelf(Value *rhs) : RHS(rhs) {}
4583 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4584 Instruction *apply(BinaryOperator &Xor) const {
4585 return &Xor;
4586 }
4587};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004588
4589
Chris Lattner7e708292002-06-25 16:13:24 +00004590Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004591 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004592 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004593
Evan Chengd34af782008-03-25 20:07:13 +00004594 if (isa<UndefValue>(Op1)) {
4595 if (isa<UndefValue>(Op0))
4596 // Handle undef ^ undef -> 0 special case. This is a common
4597 // idiom (misuse).
4598 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004599 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004600 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004601
Chris Lattnerc317d392004-02-16 01:20:27 +00004602 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4603 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004604 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004605 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004606 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004607
4608 // See if we can simplify any instructions used by the instruction whose sole
4609 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004610 if (!isa<VectorType>(I.getType())) {
4611 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4612 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4613 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4614 KnownZero, KnownOne))
4615 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004616 } else if (isa<ConstantAggregateZero>(Op1)) {
4617 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004618 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004619
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004620 // Is this a ~ operation?
4621 if (Value *NotOp = dyn_castNotVal(&I)) {
4622 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4623 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4624 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4625 if (Op0I->getOpcode() == Instruction::And ||
4626 Op0I->getOpcode() == Instruction::Or) {
4627 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4628 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4629 Instruction *NotY =
4630 BinaryOperator::createNot(Op0I->getOperand(1),
4631 Op0I->getOperand(1)->getName()+".not");
4632 InsertNewInstBefore(NotY, I);
4633 if (Op0I->getOpcode() == Instruction::And)
4634 return BinaryOperator::createOr(Op0NotVal, NotY);
4635 else
4636 return BinaryOperator::createAnd(Op0NotVal, NotY);
4637 }
4638 }
4639 }
4640 }
4641
4642
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004643 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004644 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4645 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4646 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004647 return new ICmpInst(ICI->getInversePredicate(),
4648 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004649
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004650 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4651 return new FCmpInst(FCI->getInversePredicate(),
4652 FCI->getOperand(0), FCI->getOperand(1));
4653 }
4654
Reid Spencere4d87aa2006-12-23 06:05:41 +00004655 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004656 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004657 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4658 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004659 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4660 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004661 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004662 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004663 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004664
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004665 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004666 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004667 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004668 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004669 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4670 return BinaryOperator::createSub(
4671 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004672 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004673 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004674 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004675 // (X + C) ^ signbit -> (X + C + signbit)
4676 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4677 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004678
Chris Lattner7c4049c2004-01-12 19:35:11 +00004679 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004680 } else if (Op0I->getOpcode() == Instruction::Or) {
4681 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004682 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004683 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4684 // Anything in both C1 and C2 is known to be zero, remove it from
4685 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004686 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004687 NewRHS = ConstantExpr::getAnd(NewRHS,
4688 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004689 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004690 I.setOperand(0, Op0I->getOperand(0));
4691 I.setOperand(1, NewRHS);
4692 return &I;
4693 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004694 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004695 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004696 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004697
4698 // Try to fold constant and into select arguments.
4699 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004700 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004701 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004702 if (isa<PHINode>(Op0))
4703 if (Instruction *NV = FoldOpIntoPhi(I))
4704 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004705 }
4706
Chris Lattner8d969642003-03-10 23:06:50 +00004707 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004708 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004709 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004710
Chris Lattner8d969642003-03-10 23:06:50 +00004711 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004712 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004713 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004714
Chris Lattner318bf792007-03-18 22:51:34 +00004715
4716 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4717 if (Op1I) {
4718 Value *A, *B;
4719 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4720 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004721 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004722 I.swapOperands();
4723 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004724 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004725 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004726 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004727 }
Chris Lattner318bf792007-03-18 22:51:34 +00004728 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4729 if (Op0 == A) // A^(A^B) == B
4730 return ReplaceInstUsesWith(I, B);
4731 else if (Op0 == B) // A^(B^A) == B
4732 return ReplaceInstUsesWith(I, A);
4733 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004734 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004735 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004736 std::swap(A, B);
4737 }
Chris Lattner318bf792007-03-18 22:51:34 +00004738 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004739 I.swapOperands(); // Simplified below.
4740 std::swap(Op0, Op1);
4741 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004742 }
Chris Lattner318bf792007-03-18 22:51:34 +00004743 }
4744
4745 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4746 if (Op0I) {
4747 Value *A, *B;
4748 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4749 if (A == Op1) // (B|A)^B == (A|B)^B
4750 std::swap(A, B);
4751 if (B == Op1) { // (A|B)^B == A & ~B
4752 Instruction *NotB =
4753 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4754 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004755 }
Chris Lattner318bf792007-03-18 22:51:34 +00004756 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4757 if (Op1 == A) // (A^B)^A == B
4758 return ReplaceInstUsesWith(I, B);
4759 else if (Op1 == B) // (B^A)^A == B
4760 return ReplaceInstUsesWith(I, A);
4761 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4762 if (A == Op1) // (A&B)^A -> (B&A)^A
4763 std::swap(A, B);
4764 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004765 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004766 Instruction *N =
4767 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004768 return BinaryOperator::createAnd(N, Op1);
4769 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004770 }
Chris Lattner318bf792007-03-18 22:51:34 +00004771 }
4772
4773 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4774 if (Op0I && Op1I && Op0I->isShift() &&
4775 Op0I->getOpcode() == Op1I->getOpcode() &&
4776 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4777 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4778 Instruction *NewOp =
4779 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4780 Op1I->getOperand(0),
4781 Op0I->getName()), I);
4782 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4783 Op1I->getOperand(1));
4784 }
4785
4786 if (Op0I && Op1I) {
4787 Value *A, *B, *C, *D;
4788 // (A & B)^(A | B) -> A ^ B
4789 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4790 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4791 if ((A == C && B == D) || (A == D && B == C))
4792 return BinaryOperator::createXor(A, B);
4793 }
4794 // (A | B)^(A & B) -> A ^ B
4795 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4796 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4797 if ((A == C && B == D) || (A == D && B == C))
4798 return BinaryOperator::createXor(A, B);
4799 }
4800
4801 // (A & B)^(C & D)
4802 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4803 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4804 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4805 // (X & Y)^(X & Y) -> (Y^Z) & X
4806 Value *X = 0, *Y = 0, *Z = 0;
4807 if (A == C)
4808 X = A, Y = B, Z = D;
4809 else if (A == D)
4810 X = A, Y = B, Z = C;
4811 else if (B == C)
4812 X = B, Y = A, Z = D;
4813 else if (B == D)
4814 X = B, Y = A, Z = C;
4815
4816 if (X) {
4817 Instruction *NewOp =
4818 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4819 return BinaryOperator::createAnd(NewOp, X);
4820 }
4821 }
4822 }
4823
Reid Spencere4d87aa2006-12-23 06:05:41 +00004824 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4825 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4826 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004827 return R;
4828
Chris Lattner6fc205f2006-05-05 06:39:07 +00004829 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004830 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004831 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004832 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4833 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004834 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004835 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004836 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4837 I.getType(), TD) &&
4838 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4839 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004840 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4841 Op1C->getOperand(0),
4842 I.getName());
4843 InsertNewInstBefore(NewOp, I);
4844 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4845 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004846 }
Chris Lattner99c65742007-10-24 05:38:08 +00004847 }
Chris Lattner7e708292002-06-25 16:13:24 +00004848 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004849}
4850
Chris Lattnera96879a2004-09-29 17:40:11 +00004851/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4852/// overflowed for this type.
4853static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004854 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004855 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004856
Reid Spencere4e40032007-03-21 23:19:50 +00004857 if (IsSigned)
4858 if (In2->getValue().isNegative())
4859 return Result->getValue().sgt(In1->getValue());
4860 else
4861 return Result->getValue().slt(In1->getValue());
4862 else
4863 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004864}
4865
Chris Lattner574da9b2005-01-13 20:14:25 +00004866/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4867/// code necessary to compute the offset from the base pointer (without adding
4868/// in the base pointer). Return the result as a signed integer of intptr size.
4869static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4870 TargetData &TD = IC.getTargetData();
4871 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004872 const Type *IntPtrTy = TD.getIntPtrType();
4873 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004874
4875 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004876 unsigned IntPtrWidth = TD.getPointerSize()*8;
4877 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004878
Chris Lattner574da9b2005-01-13 20:14:25 +00004879 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4880 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004881 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004882 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4883 if (OpC->isZero()) continue;
4884
4885 // Handle a struct index, which adds its field offset to the pointer.
4886 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4887 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4888
4889 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4890 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004891 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004892 Result = IC.InsertNewInstBefore(
4893 BinaryOperator::createAdd(Result,
4894 ConstantInt::get(IntPtrTy, Size),
4895 GEP->getName()+".offs"), I);
4896 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004897 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004898
4899 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4900 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4901 Scale = ConstantExpr::getMul(OC, Scale);
4902 if (Constant *RC = dyn_cast<Constant>(Result))
4903 Result = ConstantExpr::getAdd(RC, Scale);
4904 else {
4905 // Emit an add instruction.
4906 Result = IC.InsertNewInstBefore(
4907 BinaryOperator::createAdd(Result, Scale,
4908 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004909 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004910 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004911 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004912 // Convert to correct type.
4913 if (Op->getType() != IntPtrTy) {
4914 if (Constant *OpC = dyn_cast<Constant>(Op))
4915 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4916 else
4917 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4918 Op->getName()+".c"), I);
4919 }
4920 if (Size != 1) {
4921 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4922 if (Constant *OpC = dyn_cast<Constant>(Op))
4923 Op = ConstantExpr::getMul(OpC, Scale);
4924 else // We'll let instcombine(mul) convert this to a shl if possible.
4925 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4926 GEP->getName()+".idx"), I);
4927 }
4928
4929 // Emit an add instruction.
4930 if (isa<Constant>(Op) && isa<Constant>(Result))
4931 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4932 cast<Constant>(Result));
4933 else
4934 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4935 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004936 }
4937 return Result;
4938}
4939
Reid Spencere4d87aa2006-12-23 06:05:41 +00004940/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004941/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004942Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4943 ICmpInst::Predicate Cond,
4944 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004945 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004946
4947 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4948 if (isa<PointerType>(CI->getOperand(0)->getType()))
4949 RHS = CI->getOperand(0);
4950
Chris Lattner574da9b2005-01-13 20:14:25 +00004951 Value *PtrBase = GEPLHS->getOperand(0);
4952 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004953 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4954 // This transformation is valid because we know pointers can't overflow.
4955 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4956 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4957 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004958 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004959 // If the base pointers are different, but the indices are the same, just
4960 // compare the base pointer.
4961 if (PtrBase != GEPRHS->getOperand(0)) {
4962 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004963 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004964 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004965 if (IndicesTheSame)
4966 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4967 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4968 IndicesTheSame = false;
4969 break;
4970 }
4971
4972 // If all indices are the same, just compare the base pointers.
4973 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004974 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4975 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004976
4977 // Otherwise, the base pointers are different and the indices are
4978 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004979 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004980 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004981
Chris Lattnere9d782b2005-01-13 22:25:21 +00004982 // If one of the GEPs has all zero indices, recurse.
4983 bool AllZeros = true;
4984 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4985 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4986 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4987 AllZeros = false;
4988 break;
4989 }
4990 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004991 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4992 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004993
4994 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004995 AllZeros = true;
4996 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4997 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4998 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4999 AllZeros = false;
5000 break;
5001 }
5002 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005003 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005004
Chris Lattner4401c9c2005-01-14 00:20:05 +00005005 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5006 // If the GEPs only differ by one index, compare it.
5007 unsigned NumDifferences = 0; // Keep track of # differences.
5008 unsigned DiffOperand = 0; // The operand that differs.
5009 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5010 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005011 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5012 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005013 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005014 NumDifferences = 2;
5015 break;
5016 } else {
5017 if (NumDifferences++) break;
5018 DiffOperand = i;
5019 }
5020 }
5021
5022 if (NumDifferences == 0) // SAME GEP?
5023 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005024 ConstantInt::get(Type::Int1Ty,
5025 isTrueWhenEqual(Cond)));
5026
Chris Lattner4401c9c2005-01-14 00:20:05 +00005027 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005028 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5029 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005030 // Make sure we do a signed comparison here.
5031 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005032 }
5033 }
5034
Reid Spencere4d87aa2006-12-23 06:05:41 +00005035 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005036 // the result to fold to a constant!
5037 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5038 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5039 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5040 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5041 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005042 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005043 }
5044 }
5045 return 0;
5046}
5047
Reid Spencere4d87aa2006-12-23 06:05:41 +00005048Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5049 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005050 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005051
Chris Lattner58e97462007-01-14 19:42:17 +00005052 // Fold trivial predicates.
5053 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5054 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5055 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5056 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5057
5058 // Simplify 'fcmp pred X, X'
5059 if (Op0 == Op1) {
5060 switch (I.getPredicate()) {
5061 default: assert(0 && "Unknown predicate!");
5062 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5063 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5064 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5065 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5066 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5067 case FCmpInst::FCMP_OLT: // True if ordered and less than
5068 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5069 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5070
5071 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5072 case FCmpInst::FCMP_ULT: // True if unordered or less than
5073 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5074 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5075 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5076 I.setPredicate(FCmpInst::FCMP_UNO);
5077 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5078 return &I;
5079
5080 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5081 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5082 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5083 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5084 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5085 I.setPredicate(FCmpInst::FCMP_ORD);
5086 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5087 return &I;
5088 }
5089 }
5090
Reid Spencere4d87aa2006-12-23 06:05:41 +00005091 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005092 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005093
Reid Spencere4d87aa2006-12-23 06:05:41 +00005094 // Handle fcmp with constant RHS
5095 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5096 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5097 switch (LHSI->getOpcode()) {
5098 case Instruction::PHI:
5099 if (Instruction *NV = FoldOpIntoPhi(I))
5100 return NV;
5101 break;
5102 case Instruction::Select:
5103 // If either operand of the select is a constant, we can fold the
5104 // comparison into the select arms, which will cause one to be
5105 // constant folded and the select turned into a bitwise or.
5106 Value *Op1 = 0, *Op2 = 0;
5107 if (LHSI->hasOneUse()) {
5108 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5109 // Fold the known value into the constant operand.
5110 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5111 // Insert a new FCmp of the other select operand.
5112 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5113 LHSI->getOperand(2), RHSC,
5114 I.getName()), I);
5115 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5116 // Fold the known value into the constant operand.
5117 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5118 // Insert a new FCmp of the other select operand.
5119 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5120 LHSI->getOperand(1), RHSC,
5121 I.getName()), I);
5122 }
5123 }
5124
5125 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005126 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005127 break;
5128 }
5129 }
5130
5131 return Changed ? &I : 0;
5132}
5133
5134Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5135 bool Changed = SimplifyCompare(I);
5136 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5137 const Type *Ty = Op0->getType();
5138
5139 // icmp X, X
5140 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005141 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5142 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005143
5144 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005145 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005146
Reid Spencere4d87aa2006-12-23 06:05:41 +00005147 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005148 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005149 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5150 isa<ConstantPointerNull>(Op0)) &&
5151 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005152 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005153 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5154 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00005155
Reid Spencere4d87aa2006-12-23 06:05:41 +00005156 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005157 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005158 switch (I.getPredicate()) {
5159 default: assert(0 && "Invalid icmp instruction!");
5160 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00005161 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005162 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005163 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005164 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005165 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00005166 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005167
Reid Spencere4d87aa2006-12-23 06:05:41 +00005168 case ICmpInst::ICMP_UGT:
5169 case ICmpInst::ICMP_SGT:
5170 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005171 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005172 case ICmpInst::ICMP_ULT:
5173 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00005174 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5175 InsertNewInstBefore(Not, I);
5176 return BinaryOperator::createAnd(Not, Op1);
5177 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005178 case ICmpInst::ICMP_UGE:
5179 case ICmpInst::ICMP_SGE:
5180 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005181 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005182 case ICmpInst::ICMP_ULE:
5183 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00005184 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5185 InsertNewInstBefore(Not, I);
5186 return BinaryOperator::createOr(Not, Op1);
5187 }
5188 }
Chris Lattner8b170942002-08-09 23:47:40 +00005189 }
5190
Chris Lattner2be51ae2004-06-09 04:24:29 +00005191 // See if we are doing a comparison between a constant and an instruction that
5192 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005193 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005194 Value *A, *B;
5195
Chris Lattnerb6566012008-01-05 01:18:20 +00005196 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5197 if (I.isEquality() && CI->isNullValue() &&
5198 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5199 // (icmp cond A B) if cond is equality
5200 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005201 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005202
Reid Spencere4d87aa2006-12-23 06:05:41 +00005203 switch (I.getPredicate()) {
5204 default: break;
5205 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5206 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005207 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005208 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5209 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5210 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5211 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005212 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5213 if (CI->isMinValue(true))
5214 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5215 ConstantInt::getAllOnesValue(Op0->getType()));
5216
Reid Spencere4d87aa2006-12-23 06:05:41 +00005217 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005218
Reid Spencere4d87aa2006-12-23 06:05:41 +00005219 case ICmpInst::ICMP_SLT:
5220 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005221 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005222 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5223 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5224 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5225 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5226 break;
5227
5228 case ICmpInst::ICMP_UGT:
5229 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005230 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005231 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5232 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5233 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5234 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005235
5236 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5237 if (CI->isMaxValue(true))
5238 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5239 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005240 break;
5241
5242 case ICmpInst::ICMP_SGT:
5243 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005244 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005245 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5246 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5247 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5248 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5249 break;
5250
5251 case ICmpInst::ICMP_ULE:
5252 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005253 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005254 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5255 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5256 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5257 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5258 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005259
Reid Spencere4d87aa2006-12-23 06:05:41 +00005260 case ICmpInst::ICMP_SLE:
5261 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005262 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005263 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5264 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5265 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5266 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5267 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005268
Reid Spencere4d87aa2006-12-23 06:05:41 +00005269 case ICmpInst::ICMP_UGE:
5270 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005271 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005272 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5273 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5274 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5275 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5276 break;
5277
5278 case ICmpInst::ICMP_SGE:
5279 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005280 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005281 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5282 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5283 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5284 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5285 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005286 }
5287
Reid Spencere4d87aa2006-12-23 06:05:41 +00005288 // If we still have a icmp le or icmp ge instruction, turn it into the
5289 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005290 // already been handled above, this requires little checking.
5291 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005292 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005293 default: break;
5294 case ICmpInst::ICMP_ULE:
5295 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5296 case ICmpInst::ICMP_SLE:
5297 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5298 case ICmpInst::ICMP_UGE:
5299 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5300 case ICmpInst::ICMP_SGE:
5301 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005302 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005303
5304 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005305 // in the input. If this comparison is a normal comparison, it demands all
5306 // bits, if it is a sign bit comparison, it only demands the sign bit.
5307
5308 bool UnusedBit;
5309 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5310
Reid Spencer0460fb32007-03-22 20:36:03 +00005311 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5312 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005313 if (SimplifyDemandedBits(Op0,
5314 isSignBit ? APInt::getSignBit(BitWidth)
5315 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005316 KnownZero, KnownOne, 0))
5317 return &I;
5318
5319 // Given the known and unknown bits, compute a range that the LHS could be
5320 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005321 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005322 // Compute the Min, Max and RHS values based on the known bits. For the
5323 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005324 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5325 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005326 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005327 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5328 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005329 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005330 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5331 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005332 }
5333 switch (I.getPredicate()) { // LE/GE have been folded already.
5334 default: assert(0 && "Unknown icmp opcode!");
5335 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005336 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005337 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005338 break;
5339 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005340 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005341 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005342 break;
5343 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005344 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005345 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005346 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005347 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005348 break;
5349 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005350 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005351 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005352 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005353 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005354 break;
5355 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005356 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005357 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005358 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005359 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005360 break;
5361 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005362 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005363 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005364 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005365 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005366 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005367 }
5368 }
5369
Reid Spencere4d87aa2006-12-23 06:05:41 +00005370 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005371 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005372 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005373 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005374 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5375 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005376 }
5377
Chris Lattner01deb9d2007-04-03 17:43:25 +00005378 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005379 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5380 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5381 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005382 case Instruction::GetElementPtr:
5383 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005384 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005385 bool isAllZeros = true;
5386 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5387 if (!isa<Constant>(LHSI->getOperand(i)) ||
5388 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5389 isAllZeros = false;
5390 break;
5391 }
5392 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005393 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005394 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5395 }
5396 break;
5397
Chris Lattner6970b662005-04-23 15:31:55 +00005398 case Instruction::PHI:
5399 if (Instruction *NV = FoldOpIntoPhi(I))
5400 return NV;
5401 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005402 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005403 // If either operand of the select is a constant, we can fold the
5404 // comparison into the select arms, which will cause one to be
5405 // constant folded and the select turned into a bitwise or.
5406 Value *Op1 = 0, *Op2 = 0;
5407 if (LHSI->hasOneUse()) {
5408 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5409 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005410 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5411 // Insert a new ICmp of the other select operand.
5412 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5413 LHSI->getOperand(2), RHSC,
5414 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005415 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5416 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005417 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5418 // Insert a new ICmp of the other select operand.
5419 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5420 LHSI->getOperand(1), RHSC,
5421 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005422 }
5423 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005424
Chris Lattner6970b662005-04-23 15:31:55 +00005425 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005426 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005427 break;
5428 }
Chris Lattner4802d902007-04-06 18:57:34 +00005429 case Instruction::Malloc:
5430 // If we have (malloc != null), and if the malloc has a single use, we
5431 // can assume it is successful and remove the malloc.
5432 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5433 AddToWorkList(LHSI);
5434 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5435 !isTrueWhenEqual(I)));
5436 }
5437 break;
5438 }
Chris Lattner6970b662005-04-23 15:31:55 +00005439 }
5440
Reid Spencere4d87aa2006-12-23 06:05:41 +00005441 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005442 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005443 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005444 return NI;
5445 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005446 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5447 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005448 return NI;
5449
Reid Spencere4d87aa2006-12-23 06:05:41 +00005450 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005451 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5452 // now.
5453 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5454 if (isa<PointerType>(Op0->getType()) &&
5455 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005456 // We keep moving the cast from the left operand over to the right
5457 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005458 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005459
Chris Lattner57d86372007-01-06 01:45:59 +00005460 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5461 // so eliminate it as well.
5462 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5463 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005464
Chris Lattnerde90b762003-11-03 04:25:02 +00005465 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005466 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005467 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005468 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005469 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005470 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005471 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005472 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005473 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005474 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005475 }
Chris Lattner57d86372007-01-06 01:45:59 +00005476 }
5477
5478 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005479 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005480 // This comes up when you have code like
5481 // int X = A < B;
5482 // if (X) ...
5483 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005484 // with a constant or another cast from the same type.
5485 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005486 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005487 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005488 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005489
Chris Lattner65b72ba2006-09-18 04:22:48 +00005490 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005491 Value *A, *B, *C, *D;
5492 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5493 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5494 Value *OtherVal = A == Op1 ? B : A;
5495 return new ICmpInst(I.getPredicate(), OtherVal,
5496 Constant::getNullValue(A->getType()));
5497 }
5498
5499 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5500 // A^c1 == C^c2 --> A == C^(c1^c2)
5501 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5502 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5503 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005504 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005505 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5506 return new ICmpInst(I.getPredicate(), A,
5507 InsertNewInstBefore(Xor, I));
5508 }
5509
5510 // A^B == A^D -> B == D
5511 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5512 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5513 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5514 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5515 }
5516 }
5517
5518 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5519 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005520 // A == (A^B) -> B == 0
5521 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005522 return new ICmpInst(I.getPredicate(), OtherVal,
5523 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005524 }
5525 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005526 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005527 return new ICmpInst(I.getPredicate(), B,
5528 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005529 }
5530 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005531 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005532 return new ICmpInst(I.getPredicate(), B,
5533 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005534 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005535
Chris Lattner9c2328e2006-11-14 06:06:06 +00005536 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5537 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5538 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5539 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5540 Value *X = 0, *Y = 0, *Z = 0;
5541
5542 if (A == C) {
5543 X = B; Y = D; Z = A;
5544 } else if (A == D) {
5545 X = B; Y = C; Z = A;
5546 } else if (B == C) {
5547 X = A; Y = D; Z = B;
5548 } else if (B == D) {
5549 X = A; Y = C; Z = B;
5550 }
5551
5552 if (X) { // Build (X^Y) & Z
5553 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5554 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5555 I.setOperand(0, Op1);
5556 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5557 return &I;
5558 }
5559 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005560 }
Chris Lattner7e708292002-06-25 16:13:24 +00005561 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005562}
5563
Chris Lattner562ef782007-06-20 23:46:26 +00005564
5565/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5566/// and CmpRHS are both known to be integer constants.
5567Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5568 ConstantInt *DivRHS) {
5569 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5570 const APInt &CmpRHSV = CmpRHS->getValue();
5571
5572 // FIXME: If the operand types don't match the type of the divide
5573 // then don't attempt this transform. The code below doesn't have the
5574 // logic to deal with a signed divide and an unsigned compare (and
5575 // vice versa). This is because (x /s C1) <s C2 produces different
5576 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5577 // (x /u C1) <u C2. Simply casting the operands and result won't
5578 // work. :( The if statement below tests that condition and bails
5579 // if it finds it.
5580 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5581 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5582 return 0;
5583 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005584 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005585
5586 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5587 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5588 // C2 (CI). By solving for X we can turn this into a range check
5589 // instead of computing a divide.
5590 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5591
5592 // Determine if the product overflows by seeing if the product is
5593 // not equal to the divide. Make sure we do the same kind of divide
5594 // as in the LHS instruction that we're folding.
5595 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5596 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5597
5598 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005599 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005600
Chris Lattner1dbfd482007-06-21 18:11:19 +00005601 // Figure out the interval that is being checked. For example, a comparison
5602 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5603 // Compute this interval based on the constants involved and the signedness of
5604 // the compare/divide. This computes a half-open interval, keeping track of
5605 // whether either value in the interval overflows. After analysis each
5606 // overflow variable is set to 0 if it's corresponding bound variable is valid
5607 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5608 int LoOverflow = 0, HiOverflow = 0;
5609 ConstantInt *LoBound = 0, *HiBound = 0;
5610
5611
Chris Lattner562ef782007-06-20 23:46:26 +00005612 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005613 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005614 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005615 HiOverflow = LoOverflow = ProdOV;
5616 if (!HiOverflow)
5617 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005618 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005619 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005620 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005621 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5622 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005623 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005624 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5625 HiOverflow = LoOverflow = ProdOV;
5626 if (!HiOverflow)
5627 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005628 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005629 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005630 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5631 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005632 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005633 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005634 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005635 }
Dan Gohman76491272008-02-13 22:09:18 +00005636 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005637 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005638 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005639 LoBound = AddOne(DivRHS);
5640 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005641 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5642 HiOverflow = 1; // [INTMIN+1, overflow)
5643 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5644 }
Dan Gohman76491272008-02-13 22:09:18 +00005645 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005646 // e.g. X/-5 op 3 --> [-19, -14)
5647 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005648 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005649 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005650 HiBound = AddOne(Prod);
5651 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005652 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005653 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005654 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005655 HiBound = Subtract(Prod, DivRHS);
5656 }
5657
Chris Lattner1dbfd482007-06-21 18:11:19 +00005658 // Dividing by a negative swaps the condition. LT <-> GT
5659 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005660 }
5661
5662 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005663 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005664 default: assert(0 && "Unhandled icmp opcode!");
5665 case ICmpInst::ICMP_EQ:
5666 if (LoOverflow && HiOverflow)
5667 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5668 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005669 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005670 ICmpInst::ICMP_UGE, X, LoBound);
5671 else if (LoOverflow)
5672 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5673 ICmpInst::ICMP_ULT, X, HiBound);
5674 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005675 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005676 case ICmpInst::ICMP_NE:
5677 if (LoOverflow && HiOverflow)
5678 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5679 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005680 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005681 ICmpInst::ICMP_ULT, X, LoBound);
5682 else if (LoOverflow)
5683 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5684 ICmpInst::ICMP_UGE, X, HiBound);
5685 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005686 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005687 case ICmpInst::ICMP_ULT:
5688 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005689 if (LoOverflow == +1) // Low bound is greater than input range.
5690 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5691 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005692 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005693 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005694 case ICmpInst::ICMP_UGT:
5695 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005696 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005697 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005698 else if (HiOverflow == -1) // High bound less than input range.
5699 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5700 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005701 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5702 else
5703 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5704 }
5705}
5706
5707
Chris Lattner01deb9d2007-04-03 17:43:25 +00005708/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5709///
5710Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5711 Instruction *LHSI,
5712 ConstantInt *RHS) {
5713 const APInt &RHSV = RHS->getValue();
5714
5715 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005716 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005717 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5718 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5719 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005720 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5721 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005722 Value *CompareVal = LHSI->getOperand(0);
5723
5724 // If the sign bit of the XorCST is not set, there is no change to
5725 // the operation, just stop using the Xor.
5726 if (!XorCST->getValue().isNegative()) {
5727 ICI.setOperand(0, CompareVal);
5728 AddToWorkList(LHSI);
5729 return &ICI;
5730 }
5731
5732 // Was the old condition true if the operand is positive?
5733 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5734
5735 // If so, the new one isn't.
5736 isTrueIfPositive ^= true;
5737
5738 if (isTrueIfPositive)
5739 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5740 else
5741 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5742 }
5743 }
5744 break;
5745 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5746 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5747 LHSI->getOperand(0)->hasOneUse()) {
5748 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5749
5750 // If the LHS is an AND of a truncating cast, we can widen the
5751 // and/compare to be the input width without changing the value
5752 // produced, eliminating a cast.
5753 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5754 // We can do this transformation if either the AND constant does not
5755 // have its sign bit set or if it is an equality comparison.
5756 // Extending a relational comparison when we're checking the sign
5757 // bit would not work.
5758 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005759 (ICI.isEquality() ||
5760 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005761 uint32_t BitWidth =
5762 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5763 APInt NewCST = AndCST->getValue();
5764 NewCST.zext(BitWidth);
5765 APInt NewCI = RHSV;
5766 NewCI.zext(BitWidth);
5767 Instruction *NewAnd =
5768 BinaryOperator::createAnd(Cast->getOperand(0),
5769 ConstantInt::get(NewCST),LHSI->getName());
5770 InsertNewInstBefore(NewAnd, ICI);
5771 return new ICmpInst(ICI.getPredicate(), NewAnd,
5772 ConstantInt::get(NewCI));
5773 }
5774 }
5775
5776 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5777 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5778 // happens a LOT in code produced by the C front-end, for bitfield
5779 // access.
5780 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5781 if (Shift && !Shift->isShift())
5782 Shift = 0;
5783
5784 ConstantInt *ShAmt;
5785 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5786 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5787 const Type *AndTy = AndCST->getType(); // Type of the and.
5788
5789 // We can fold this as long as we can't shift unknown bits
5790 // into the mask. This can only happen with signed shift
5791 // rights, as they sign-extend.
5792 if (ShAmt) {
5793 bool CanFold = Shift->isLogicalShift();
5794 if (!CanFold) {
5795 // To test for the bad case of the signed shr, see if any
5796 // of the bits shifted in could be tested after the mask.
5797 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5798 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5799
5800 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5801 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5802 AndCST->getValue()) == 0)
5803 CanFold = true;
5804 }
5805
5806 if (CanFold) {
5807 Constant *NewCst;
5808 if (Shift->getOpcode() == Instruction::Shl)
5809 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5810 else
5811 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5812
5813 // Check to see if we are shifting out any of the bits being
5814 // compared.
5815 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5816 // If we shifted bits out, the fold is not going to work out.
5817 // As a special case, check to see if this means that the
5818 // result is always true or false now.
5819 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5820 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5821 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5822 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5823 } else {
5824 ICI.setOperand(1, NewCst);
5825 Constant *NewAndCST;
5826 if (Shift->getOpcode() == Instruction::Shl)
5827 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5828 else
5829 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5830 LHSI->setOperand(1, NewAndCST);
5831 LHSI->setOperand(0, Shift->getOperand(0));
5832 AddToWorkList(Shift); // Shift is dead.
5833 AddUsesToWorkList(ICI);
5834 return &ICI;
5835 }
5836 }
5837 }
5838
5839 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5840 // preferable because it allows the C<<Y expression to be hoisted out
5841 // of a loop if Y is invariant and X is not.
5842 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5843 ICI.isEquality() && !Shift->isArithmeticShift() &&
5844 isa<Instruction>(Shift->getOperand(0))) {
5845 // Compute C << Y.
5846 Value *NS;
5847 if (Shift->getOpcode() == Instruction::LShr) {
5848 NS = BinaryOperator::createShl(AndCST,
5849 Shift->getOperand(1), "tmp");
5850 } else {
5851 // Insert a logical shift.
5852 NS = BinaryOperator::createLShr(AndCST,
5853 Shift->getOperand(1), "tmp");
5854 }
5855 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5856
5857 // Compute X & (C << Y).
5858 Instruction *NewAnd =
5859 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5860 InsertNewInstBefore(NewAnd, ICI);
5861
5862 ICI.setOperand(0, NewAnd);
5863 return &ICI;
5864 }
5865 }
5866 break;
5867
Chris Lattnera0141b92007-07-15 20:42:37 +00005868 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5869 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5870 if (!ShAmt) break;
5871
5872 uint32_t TypeBits = RHSV.getBitWidth();
5873
5874 // Check that the shift amount is in range. If not, don't perform
5875 // undefined shifts. When the shift is visited it will be
5876 // simplified.
5877 if (ShAmt->uge(TypeBits))
5878 break;
5879
5880 if (ICI.isEquality()) {
5881 // If we are comparing against bits always shifted out, the
5882 // comparison cannot succeed.
5883 Constant *Comp =
5884 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5885 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5886 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5887 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5888 return ReplaceInstUsesWith(ICI, Cst);
5889 }
5890
5891 if (LHSI->hasOneUse()) {
5892 // Otherwise strength reduce the shift into an and.
5893 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5894 Constant *Mask =
5895 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005896
Chris Lattnera0141b92007-07-15 20:42:37 +00005897 Instruction *AndI =
5898 BinaryOperator::createAnd(LHSI->getOperand(0),
5899 Mask, LHSI->getName()+".mask");
5900 Value *And = InsertNewInstBefore(AndI, ICI);
5901 return new ICmpInst(ICI.getPredicate(), And,
5902 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005903 }
5904 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005905
5906 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5907 bool TrueIfSigned = false;
5908 if (LHSI->hasOneUse() &&
5909 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5910 // (X << 31) <s 0 --> (X&1) != 0
5911 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5912 (TypeBits-ShAmt->getZExtValue()-1));
5913 Instruction *AndI =
5914 BinaryOperator::createAnd(LHSI->getOperand(0),
5915 Mask, LHSI->getName()+".mask");
5916 Value *And = InsertNewInstBefore(AndI, ICI);
5917
5918 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5919 And, Constant::getNullValue(And->getType()));
5920 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005921 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005922 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005923
5924 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005925 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005926 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005927 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005928 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005929
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005930 // Check that the shift amount is in range. If not, don't perform
5931 // undefined shifts. When the shift is visited it will be
5932 // simplified.
5933 uint32_t TypeBits = RHSV.getBitWidth();
5934 if (ShAmt->uge(TypeBits))
5935 break;
5936
5937 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005938
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005939 // If we are comparing against bits always shifted out, the
5940 // comparison cannot succeed.
5941 APInt Comp = RHSV << ShAmtVal;
5942 if (LHSI->getOpcode() == Instruction::LShr)
5943 Comp = Comp.lshr(ShAmtVal);
5944 else
5945 Comp = Comp.ashr(ShAmtVal);
5946
5947 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5948 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5949 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5950 return ReplaceInstUsesWith(ICI, Cst);
5951 }
5952
5953 // Otherwise, check to see if the bits shifted out are known to be zero.
5954 // If so, we can compare against the unshifted value:
5955 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
5956 if (MaskedValueIsZero(LHSI->getOperand(0),
5957 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5958 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5959 ConstantExpr::getShl(RHS, ShAmt));
5960 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005961
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005962 if (LHSI->hasOneUse() || RHSV == 0) {
5963 // Otherwise strength reduce the shift into an and.
5964 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5965 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00005966
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005967 Instruction *AndI =
5968 BinaryOperator::createAnd(LHSI->getOperand(0),
5969 Mask, LHSI->getName()+".mask");
5970 Value *And = InsertNewInstBefore(AndI, ICI);
5971 return new ICmpInst(ICI.getPredicate(), And,
5972 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005973 }
5974 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005975 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005976
5977 case Instruction::SDiv:
5978 case Instruction::UDiv:
5979 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5980 // Fold this div into the comparison, producing a range check.
5981 // Determine, based on the divide type, what the range is being
5982 // checked. If there is an overflow on the low or high side, remember
5983 // it, otherwise compute the range [low, hi) bounding the new value.
5984 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005985 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5986 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5987 DivRHS))
5988 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005989 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005990
5991 case Instruction::Add:
5992 // Fold: icmp pred (add, X, C1), C2
5993
5994 if (!ICI.isEquality()) {
5995 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5996 if (!LHSC) break;
5997 const APInt &LHSV = LHSC->getValue();
5998
5999 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6000 .subtract(LHSV);
6001
6002 if (ICI.isSignedPredicate()) {
6003 if (CR.getLower().isSignBit()) {
6004 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6005 ConstantInt::get(CR.getUpper()));
6006 } else if (CR.getUpper().isSignBit()) {
6007 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6008 ConstantInt::get(CR.getLower()));
6009 }
6010 } else {
6011 if (CR.getLower().isMinValue()) {
6012 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6013 ConstantInt::get(CR.getUpper()));
6014 } else if (CR.getUpper().isMinValue()) {
6015 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6016 ConstantInt::get(CR.getLower()));
6017 }
6018 }
6019 }
6020 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006021 }
6022
6023 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6024 if (ICI.isEquality()) {
6025 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6026
6027 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6028 // the second operand is a constant, simplify a bit.
6029 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6030 switch (BO->getOpcode()) {
6031 case Instruction::SRem:
6032 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6033 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6034 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6035 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6036 Instruction *NewRem =
6037 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
6038 BO->getName());
6039 InsertNewInstBefore(NewRem, ICI);
6040 return new ICmpInst(ICI.getPredicate(), NewRem,
6041 Constant::getNullValue(BO->getType()));
6042 }
6043 }
6044 break;
6045 case Instruction::Add:
6046 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6047 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6048 if (BO->hasOneUse())
6049 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6050 Subtract(RHS, BOp1C));
6051 } else if (RHSV == 0) {
6052 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6053 // efficiently invertible, or if the add has just this one use.
6054 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6055
6056 if (Value *NegVal = dyn_castNegVal(BOp1))
6057 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6058 else if (Value *NegVal = dyn_castNegVal(BOp0))
6059 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6060 else if (BO->hasOneUse()) {
6061 Instruction *Neg = BinaryOperator::createNeg(BOp1);
6062 InsertNewInstBefore(Neg, ICI);
6063 Neg->takeName(BO);
6064 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6065 }
6066 }
6067 break;
6068 case Instruction::Xor:
6069 // For the xor case, we can xor two constants together, eliminating
6070 // the explicit xor.
6071 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6072 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6073 ConstantExpr::getXor(RHS, BOC));
6074
6075 // FALLTHROUGH
6076 case Instruction::Sub:
6077 // Replace (([sub|xor] A, B) != 0) with (A != B)
6078 if (RHSV == 0)
6079 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6080 BO->getOperand(1));
6081 break;
6082
6083 case Instruction::Or:
6084 // If bits are being or'd in that are not present in the constant we
6085 // are comparing against, then the comparison could never succeed!
6086 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6087 Constant *NotCI = ConstantExpr::getNot(RHS);
6088 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6089 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6090 isICMP_NE));
6091 }
6092 break;
6093
6094 case Instruction::And:
6095 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6096 // If bits are being compared against that are and'd out, then the
6097 // comparison can never succeed!
6098 if ((RHSV & ~BOC->getValue()) != 0)
6099 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6100 isICMP_NE));
6101
6102 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6103 if (RHS == BOC && RHSV.isPowerOf2())
6104 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6105 ICmpInst::ICMP_NE, LHSI,
6106 Constant::getNullValue(RHS->getType()));
6107
6108 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6109 if (isSignBit(BOC)) {
6110 Value *X = BO->getOperand(0);
6111 Constant *Zero = Constant::getNullValue(X->getType());
6112 ICmpInst::Predicate pred = isICMP_NE ?
6113 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6114 return new ICmpInst(pred, X, Zero);
6115 }
6116
6117 // ((X & ~7) == 0) --> X < 8
6118 if (RHSV == 0 && isHighOnes(BOC)) {
6119 Value *X = BO->getOperand(0);
6120 Constant *NegX = ConstantExpr::getNeg(BOC);
6121 ICmpInst::Predicate pred = isICMP_NE ?
6122 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6123 return new ICmpInst(pred, X, NegX);
6124 }
6125 }
6126 default: break;
6127 }
6128 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6129 // Handle icmp {eq|ne} <intrinsic>, intcst.
6130 if (II->getIntrinsicID() == Intrinsic::bswap) {
6131 AddToWorkList(II);
6132 ICI.setOperand(0, II->getOperand(1));
6133 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6134 return &ICI;
6135 }
6136 }
6137 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006138 // If the LHS is a cast from an integral value of the same size,
6139 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006140 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6141 Value *CastOp = Cast->getOperand(0);
6142 const Type *SrcTy = CastOp->getType();
6143 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6144 if (SrcTy->isInteger() &&
6145 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6146 // If this is an unsigned comparison, try to make the comparison use
6147 // smaller constant values.
6148 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6149 // X u< 128 => X s> -1
6150 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6151 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6152 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6153 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6154 // X u> 127 => X s< 0
6155 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6156 Constant::getNullValue(SrcTy));
6157 }
6158 }
6159 }
6160 }
6161 return 0;
6162}
6163
6164/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6165/// We only handle extending casts so far.
6166///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006167Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6168 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006169 Value *LHSCIOp = LHSCI->getOperand(0);
6170 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006171 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006172 Value *RHSCIOp;
6173
Chris Lattner8c756c12007-05-05 22:41:33 +00006174 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6175 // integer type is the same size as the pointer type.
6176 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6177 getTargetData().getPointerSizeInBits() ==
6178 cast<IntegerType>(DestTy)->getBitWidth()) {
6179 Value *RHSOp = 0;
6180 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006181 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006182 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6183 RHSOp = RHSC->getOperand(0);
6184 // If the pointer types don't match, insert a bitcast.
6185 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006186 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006187 }
6188
6189 if (RHSOp)
6190 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6191 }
6192
6193 // The code below only handles extension cast instructions, so far.
6194 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006195 if (LHSCI->getOpcode() != Instruction::ZExt &&
6196 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006197 return 0;
6198
Reid Spencere4d87aa2006-12-23 06:05:41 +00006199 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6200 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006201
Reid Spencere4d87aa2006-12-23 06:05:41 +00006202 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006203 // Not an extension from the same type?
6204 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006205 if (RHSCIOp->getType() != LHSCIOp->getType())
6206 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006207
Nick Lewycky4189a532008-01-28 03:48:02 +00006208 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006209 // and the other is a zext), then we can't handle this.
6210 if (CI->getOpcode() != LHSCI->getOpcode())
6211 return 0;
6212
Nick Lewycky4189a532008-01-28 03:48:02 +00006213 // Deal with equality cases early.
6214 if (ICI.isEquality())
6215 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6216
6217 // A signed comparison of sign extended values simplifies into a
6218 // signed comparison.
6219 if (isSignedCmp && isSignedExt)
6220 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6221
6222 // The other three cases all fold into an unsigned comparison.
6223 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006224 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006225
Reid Spencere4d87aa2006-12-23 06:05:41 +00006226 // If we aren't dealing with a constant on the RHS, exit early
6227 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6228 if (!CI)
6229 return 0;
6230
6231 // Compute the constant that would happen if we truncated to SrcTy then
6232 // reextended to DestTy.
6233 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6234 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6235
6236 // If the re-extended constant didn't change...
6237 if (Res2 == CI) {
6238 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6239 // For example, we might have:
6240 // %A = sext short %X to uint
6241 // %B = icmp ugt uint %A, 1330
6242 // It is incorrect to transform this into
6243 // %B = icmp ugt short %X, 1330
6244 // because %A may have negative value.
6245 //
6246 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6247 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006248 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006249 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6250 else
6251 return 0;
6252 }
6253
6254 // The re-extended constant changed so the constant cannot be represented
6255 // in the shorter type. Consequently, we cannot emit a simple comparison.
6256
6257 // First, handle some easy cases. We know the result cannot be equal at this
6258 // point so handle the ICI.isEquality() cases
6259 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006260 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006261 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006262 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006263
6264 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6265 // should have been folded away previously and not enter in here.
6266 Value *Result;
6267 if (isSignedCmp) {
6268 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006269 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006270 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006271 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006272 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006273 } else {
6274 // We're performing an unsigned comparison.
6275 if (isSignedExt) {
6276 // We're performing an unsigned comp with a sign extended value.
6277 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006278 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006279 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6280 NegOne, ICI.getName()), ICI);
6281 } else {
6282 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006283 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006284 }
6285 }
6286
6287 // Finally, return the value computed.
6288 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6289 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6290 return ReplaceInstUsesWith(ICI, Result);
6291 } else {
6292 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6293 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6294 "ICmp should be folded!");
6295 if (Constant *CI = dyn_cast<Constant>(Result))
6296 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6297 else
6298 return BinaryOperator::createNot(Result);
6299 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006300}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006301
Reid Spencer832254e2007-02-02 02:16:23 +00006302Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6303 return commonShiftTransforms(I);
6304}
6305
6306Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6307 return commonShiftTransforms(I);
6308}
6309
6310Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006311 if (Instruction *R = commonShiftTransforms(I))
6312 return R;
6313
6314 Value *Op0 = I.getOperand(0);
6315
6316 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6317 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6318 if (CSI->isAllOnesValue())
6319 return ReplaceInstUsesWith(I, CSI);
6320
6321 // See if we can turn a signed shr into an unsigned shr.
6322 if (MaskedValueIsZero(Op0,
6323 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6324 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6325
6326 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006327}
6328
6329Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6330 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006331 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006332
6333 // shl X, 0 == X and shr X, 0 == X
6334 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006335 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006336 Op0 == Constant::getNullValue(Op0->getType()))
6337 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006338
Reid Spencere4d87aa2006-12-23 06:05:41 +00006339 if (isa<UndefValue>(Op0)) {
6340 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006341 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006342 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006343 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6344 }
6345 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006346 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6347 return ReplaceInstUsesWith(I, Op0);
6348 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006349 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006350 }
6351
Chris Lattner2eefe512004-04-09 19:05:30 +00006352 // Try to fold constant and into select arguments.
6353 if (isa<Constant>(Op0))
6354 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006355 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006356 return R;
6357
Reid Spencerb83eb642006-10-20 07:07:24 +00006358 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006359 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6360 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006361 return 0;
6362}
6363
Reid Spencerb83eb642006-10-20 07:07:24 +00006364Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006365 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006366 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006367
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006368 // See if we can simplify any instructions used by the instruction whose sole
6369 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006370 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6371 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6372 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006373 KnownZero, KnownOne))
6374 return &I;
6375
Chris Lattner4d5542c2006-01-06 07:12:35 +00006376 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6377 // of a signed value.
6378 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006379 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006380 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006381 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6382 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006383 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006384 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006385 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006386 }
6387
6388 // ((X*C1) << C2) == (X * (C1 << C2))
6389 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6390 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6391 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6392 return BinaryOperator::createMul(BO->getOperand(0),
6393 ConstantExpr::getShl(BOOp, Op1));
6394
6395 // Try to fold constant and into select arguments.
6396 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6397 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6398 return R;
6399 if (isa<PHINode>(Op0))
6400 if (Instruction *NV = FoldOpIntoPhi(I))
6401 return NV;
6402
Chris Lattner8999dd32007-12-22 09:07:47 +00006403 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6404 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6405 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6406 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6407 // place. Don't try to do this transformation in this case. Also, we
6408 // require that the input operand is a shift-by-constant so that we have
6409 // confidence that the shifts will get folded together. We could do this
6410 // xform in more cases, but it is unlikely to be profitable.
6411 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6412 isa<ConstantInt>(TrOp->getOperand(1))) {
6413 // Okay, we'll do this xform. Make the shift of shift.
6414 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6415 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6416 I.getName());
6417 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6418
6419 // For logical shifts, the truncation has the effect of making the high
6420 // part of the register be zeros. Emulate this by inserting an AND to
6421 // clear the top bits as needed. This 'and' will usually be zapped by
6422 // other xforms later if dead.
6423 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6424 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6425 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6426
6427 // The mask we constructed says what the trunc would do if occurring
6428 // between the shifts. We want to know the effect *after* the second
6429 // shift. We know that it is a logical shift by a constant, so adjust the
6430 // mask as appropriate.
6431 if (I.getOpcode() == Instruction::Shl)
6432 MaskV <<= Op1->getZExtValue();
6433 else {
6434 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6435 MaskV = MaskV.lshr(Op1->getZExtValue());
6436 }
6437
6438 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6439 TI->getName());
6440 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6441
6442 // Return the value truncated to the interesting size.
6443 return new TruncInst(And, I.getType());
6444 }
6445 }
6446
Chris Lattner4d5542c2006-01-06 07:12:35 +00006447 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006448 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6449 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6450 Value *V1, *V2;
6451 ConstantInt *CC;
6452 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006453 default: break;
6454 case Instruction::Add:
6455 case Instruction::And:
6456 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006457 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006458 // These operators commute.
6459 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006460 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6461 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006462 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006463 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006464 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006465 Op0BO->getName());
6466 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006467 Instruction *X =
6468 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6469 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006470 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006471 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006472 return BinaryOperator::createAnd(X, ConstantInt::get(
6473 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006474 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006475
Chris Lattner150f12a2005-09-18 06:30:59 +00006476 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006477 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006478 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006479 match(Op0BOOp1,
6480 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006481 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6482 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006483 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006484 Op0BO->getOperand(0), Op1,
6485 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006486 InsertNewInstBefore(YS, I); // (Y << C)
6487 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006488 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006489 V1->getName()+".mask");
6490 InsertNewInstBefore(XM, I); // X & (CC << C)
6491
6492 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6493 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006494 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006495
Reid Spencera07cb7d2007-02-02 14:41:37 +00006496 // FALL THROUGH.
6497 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006498 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006499 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6500 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006501 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006502 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006503 Op0BO->getOperand(1), Op1,
6504 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006505 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006506 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006507 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006508 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006509 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006510 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006511 return BinaryOperator::createAnd(X, ConstantInt::get(
6512 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006513 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006514
Chris Lattner13d4ab42006-05-31 21:14:00 +00006515 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006516 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6517 match(Op0BO->getOperand(0),
6518 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006519 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006520 cast<BinaryOperator>(Op0BO->getOperand(0))
6521 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006522 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006523 Op0BO->getOperand(1), Op1,
6524 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006525 InsertNewInstBefore(YS, I); // (Y << C)
6526 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006527 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006528 V1->getName()+".mask");
6529 InsertNewInstBefore(XM, I); // X & (CC << C)
6530
Chris Lattner13d4ab42006-05-31 21:14:00 +00006531 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006532 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006533
Chris Lattner11021cb2005-09-18 05:12:10 +00006534 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006535 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006536 }
6537
6538
6539 // If the operand is an bitwise operator with a constant RHS, and the
6540 // shift is the only use, we can pull it out of the shift.
6541 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6542 bool isValid = true; // Valid only for And, Or, Xor
6543 bool highBitSet = false; // Transform if high bit of constant set?
6544
6545 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006546 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006547 case Instruction::Add:
6548 isValid = isLeftShift;
6549 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006550 case Instruction::Or:
6551 case Instruction::Xor:
6552 highBitSet = false;
6553 break;
6554 case Instruction::And:
6555 highBitSet = true;
6556 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006557 }
6558
6559 // If this is a signed shift right, and the high bit is modified
6560 // by the logical operation, do not perform the transformation.
6561 // The highBitSet boolean indicates the value of the high bit of
6562 // the constant which would cause it to be modified for this
6563 // operation.
6564 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006565 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006566 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006567
6568 if (isValid) {
6569 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6570
6571 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006572 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006573 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006574 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006575
6576 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6577 NewRHS);
6578 }
6579 }
6580 }
6581 }
6582
Chris Lattnerad0124c2006-01-06 07:52:12 +00006583 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006584 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6585 if (ShiftOp && !ShiftOp->isShift())
6586 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006587
Reid Spencerb83eb642006-10-20 07:07:24 +00006588 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006589 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006590 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6591 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006592 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6593 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6594 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006595
Zhou Sheng4351c642007-04-02 08:20:41 +00006596 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006597 if (AmtSum > TypeBits)
6598 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006599
6600 const IntegerType *Ty = cast<IntegerType>(I.getType());
6601
6602 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006603 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006604 return BinaryOperator::create(I.getOpcode(), X,
6605 ConstantInt::get(Ty, AmtSum));
6606 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6607 I.getOpcode() == Instruction::AShr) {
6608 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6609 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6610 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6611 I.getOpcode() == Instruction::LShr) {
6612 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6613 Instruction *Shift =
6614 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6615 InsertNewInstBefore(Shift, I);
6616
Zhou Shenge9e03f62007-03-28 15:02:20 +00006617 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006618 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006619 }
6620
Chris Lattnerb87056f2007-02-05 00:57:54 +00006621 // Okay, if we get here, one shift must be left, and the other shift must be
6622 // right. See if the amounts are equal.
6623 if (ShiftAmt1 == ShiftAmt2) {
6624 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6625 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006626 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006627 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006628 }
6629 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6630 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006631 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006632 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006633 }
6634 // We can simplify ((X << C) >>s C) into a trunc + sext.
6635 // NOTE: we could do this for any C, but that would make 'unusual' integer
6636 // types. For now, just stick to ones well-supported by the code
6637 // generators.
6638 const Type *SExtType = 0;
6639 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006640 case 1 :
6641 case 8 :
6642 case 16 :
6643 case 32 :
6644 case 64 :
6645 case 128:
6646 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6647 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006648 default: break;
6649 }
6650 if (SExtType) {
6651 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6652 InsertNewInstBefore(NewTrunc, I);
6653 return new SExtInst(NewTrunc, Ty);
6654 }
6655 // Otherwise, we can't handle it yet.
6656 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006657 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006658
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006659 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006660 if (I.getOpcode() == Instruction::Shl) {
6661 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6662 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006663 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006664 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006665 InsertNewInstBefore(Shift, I);
6666
Reid Spencer55702aa2007-03-25 21:11:44 +00006667 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6668 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006669 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006670
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006671 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006672 if (I.getOpcode() == Instruction::LShr) {
6673 assert(ShiftOp->getOpcode() == Instruction::Shl);
6674 Instruction *Shift =
6675 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6676 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006677
Reid Spencerd5e30f02007-03-26 17:18:58 +00006678 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006679 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006680 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006681
6682 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6683 } else {
6684 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006685 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006686
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006687 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006688 if (I.getOpcode() == Instruction::Shl) {
6689 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6690 ShiftOp->getOpcode() == Instruction::AShr);
6691 Instruction *Shift =
6692 BinaryOperator::create(ShiftOp->getOpcode(), X,
6693 ConstantInt::get(Ty, ShiftDiff));
6694 InsertNewInstBefore(Shift, I);
6695
Reid Spencer55702aa2007-03-25 21:11:44 +00006696 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006697 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006698 }
6699
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006700 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006701 if (I.getOpcode() == Instruction::LShr) {
6702 assert(ShiftOp->getOpcode() == Instruction::Shl);
6703 Instruction *Shift =
6704 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6705 InsertNewInstBefore(Shift, I);
6706
Reid Spencer68d27cf2007-03-26 23:45:51 +00006707 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006708 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006709 }
6710
6711 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006712 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006713 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006714 return 0;
6715}
6716
Chris Lattnera1be5662002-05-02 17:06:02 +00006717
Chris Lattnercfd65102005-10-29 04:36:15 +00006718/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6719/// expression. If so, decompose it, returning some value X, such that Val is
6720/// X*Scale+Offset.
6721///
6722static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006723 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006724 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006725 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006726 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006727 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006728 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006729 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6730 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6731 if (I->getOpcode() == Instruction::Shl) {
6732 // This is a value scaled by '1 << the shift amt'.
6733 Scale = 1U << RHS->getZExtValue();
6734 Offset = 0;
6735 return I->getOperand(0);
6736 } else if (I->getOpcode() == Instruction::Mul) {
6737 // This value is scaled by 'RHS'.
6738 Scale = RHS->getZExtValue();
6739 Offset = 0;
6740 return I->getOperand(0);
6741 } else if (I->getOpcode() == Instruction::Add) {
6742 // We have X+C. Check to see if we really have (X*C2)+C1,
6743 // where C1 is divisible by C2.
6744 unsigned SubScale;
6745 Value *SubVal =
6746 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6747 Offset += RHS->getZExtValue();
6748 Scale = SubScale;
6749 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006750 }
6751 }
6752 }
6753
6754 // Otherwise, we can't look past this.
6755 Scale = 1;
6756 Offset = 0;
6757 return Val;
6758}
6759
6760
Chris Lattnerb3f83972005-10-24 06:03:58 +00006761/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6762/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006763Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006764 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006765 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006766
Chris Lattnerb53c2382005-10-24 06:22:12 +00006767 // Remove any uses of AI that are dead.
6768 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006769
Chris Lattnerb53c2382005-10-24 06:22:12 +00006770 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6771 Instruction *User = cast<Instruction>(*UI++);
6772 if (isInstructionTriviallyDead(User)) {
6773 while (UI != E && *UI == User)
6774 ++UI; // If this instruction uses AI more than once, don't break UI.
6775
Chris Lattnerb53c2382005-10-24 06:22:12 +00006776 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006777 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006778 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006779 }
6780 }
6781
Chris Lattnerb3f83972005-10-24 06:03:58 +00006782 // Get the type really allocated and the type casted to.
6783 const Type *AllocElTy = AI.getAllocatedType();
6784 const Type *CastElTy = PTy->getElementType();
6785 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006786
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006787 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6788 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006789 if (CastElTyAlign < AllocElTyAlign) return 0;
6790
Chris Lattner39387a52005-10-24 06:35:18 +00006791 // If the allocation has multiple uses, only promote it if we are strictly
6792 // increasing the alignment of the resultant allocation. If we keep it the
6793 // same, we open the door to infinite loops of various kinds.
6794 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6795
Duncan Sands514ab342007-11-01 20:53:16 +00006796 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6797 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006798 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006799
Chris Lattner455fcc82005-10-29 03:19:53 +00006800 // See if we can satisfy the modulus by pulling a scale out of the array
6801 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006802 unsigned ArraySizeScale;
6803 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006804 Value *NumElements = // See if the array size is a decomposable linear expr.
6805 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6806
Chris Lattner455fcc82005-10-29 03:19:53 +00006807 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6808 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006809 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6810 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006811
Chris Lattner455fcc82005-10-29 03:19:53 +00006812 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6813 Value *Amt = 0;
6814 if (Scale == 1) {
6815 Amt = NumElements;
6816 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006817 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006818 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6819 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006820 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006821 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006822 else if (Scale != 1) {
6823 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6824 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006825 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006826 }
6827
Jeff Cohen86796be2007-04-04 16:58:57 +00006828 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6829 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006830 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6831 Amt = InsertNewInstBefore(Tmp, AI);
6832 }
6833
Chris Lattnerb3f83972005-10-24 06:03:58 +00006834 AllocationInst *New;
6835 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006836 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006837 else
Chris Lattner6934a042007-02-11 01:23:03 +00006838 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006839 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006840 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006841
6842 // If the allocation has multiple uses, insert a cast and change all things
6843 // that used it to use the new cast. This will also hack on CI, but it will
6844 // die soon.
6845 if (!AI.hasOneUse()) {
6846 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006847 // New is the allocation instruction, pointer typed. AI is the original
6848 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6849 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006850 InsertNewInstBefore(NewCast, AI);
6851 AI.replaceAllUsesWith(NewCast);
6852 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006853 return ReplaceInstUsesWith(CI, New);
6854}
6855
Chris Lattner70074e02006-05-13 02:06:03 +00006856/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006857/// and return it as type Ty without inserting any new casts and without
6858/// changing the computed value. This is used by code that tries to decide
6859/// whether promoting or shrinking integer operations to wider or smaller types
6860/// will allow us to eliminate a truncate or extend.
6861///
6862/// This is a truncation operation if Ty is smaller than V->getType(), or an
6863/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00006864bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6865 unsigned CastOpc,
6866 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006867 // We can always evaluate constants in another type.
6868 if (isa<ConstantInt>(V))
6869 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006870
6871 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006872 if (!I) return false;
6873
6874 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006875
Chris Lattner951626b2007-08-02 06:11:14 +00006876 // If this is an extension or truncate, we can often eliminate it.
6877 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6878 // If this is a cast from the destination type, we can trivially eliminate
6879 // it, and this will remove a cast overall.
6880 if (I->getOperand(0)->getType() == Ty) {
6881 // If the first operand is itself a cast, and is eliminable, do not count
6882 // this as an eliminable cast. We would prefer to eliminate those two
6883 // casts first.
6884 if (!isa<CastInst>(I->getOperand(0)))
6885 ++NumCastsRemoved;
6886 return true;
6887 }
6888 }
6889
6890 // We can't extend or shrink something that has multiple uses: doing so would
6891 // require duplicating the instruction in general, which isn't profitable.
6892 if (!I->hasOneUse()) return false;
6893
Chris Lattner70074e02006-05-13 02:06:03 +00006894 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006895 case Instruction::Add:
6896 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006897 case Instruction::And:
6898 case Instruction::Or:
6899 case Instruction::Xor:
6900 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006901 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6902 NumCastsRemoved) &&
6903 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6904 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006905
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006906 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006907 // A multiply can be truncated by truncating its operands.
6908 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6909 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6910 NumCastsRemoved) &&
6911 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6912 NumCastsRemoved);
6913
Chris Lattner46b96052006-11-29 07:18:39 +00006914 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006915 // If we are truncating the result of this SHL, and if it's a shift of a
6916 // constant amount, we can always perform a SHL in a smaller type.
6917 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006918 uint32_t BitWidth = Ty->getBitWidth();
6919 if (BitWidth < OrigTy->getBitWidth() &&
6920 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006921 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6922 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006923 }
6924 break;
6925 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006926 // If this is a truncate of a logical shr, we can truncate it to a smaller
6927 // lshr iff we know that the bits we would otherwise be shifting in are
6928 // already zeros.
6929 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006930 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6931 uint32_t BitWidth = Ty->getBitWidth();
6932 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006933 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006934 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6935 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006936 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6937 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006938 }
6939 }
Chris Lattner46b96052006-11-29 07:18:39 +00006940 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006941 case Instruction::ZExt:
6942 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006943 case Instruction::Trunc:
6944 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006945 // can safely replace it. Note that replacing it does not reduce the number
6946 // of casts in the input.
6947 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006948 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006949
Reid Spencer3da59db2006-11-27 01:05:10 +00006950 break;
6951 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006952 // TODO: Can handle more cases here.
6953 break;
6954 }
6955
6956 return false;
6957}
6958
6959/// EvaluateInDifferentType - Given an expression that
6960/// CanEvaluateInDifferentType returns true for, actually insert the code to
6961/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006962Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006963 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006964 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006965 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006966
6967 // Otherwise, it must be an instruction.
6968 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006969 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006970 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006971 case Instruction::Add:
6972 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006973 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006974 case Instruction::And:
6975 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006976 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006977 case Instruction::AShr:
6978 case Instruction::LShr:
6979 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006980 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006981 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6982 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6983 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006984 break;
6985 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006986 case Instruction::Trunc:
6987 case Instruction::ZExt:
6988 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006989 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006990 // just return the source. There's no need to insert it because it is not
6991 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006992 if (I->getOperand(0)->getType() == Ty)
6993 return I->getOperand(0);
6994
Chris Lattner951626b2007-08-02 06:11:14 +00006995 // Otherwise, must be the same type of case, so just reinsert a new one.
6996 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6997 Ty, I->getName());
6998 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006999 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007000 // TODO: Can handle more cases here.
7001 assert(0 && "Unreachable!");
7002 break;
7003 }
7004
7005 return InsertNewInstBefore(Res, *I);
7006}
7007
Reid Spencer3da59db2006-11-27 01:05:10 +00007008/// @brief Implement the transforms common to all CastInst visitors.
7009Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007010 Value *Src = CI.getOperand(0);
7011
Dan Gohman23d9d272007-05-11 21:10:54 +00007012 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007013 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007014 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007015 if (Instruction::CastOps opc =
7016 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7017 // The first cast (CSrc) is eliminable so we need to fix up or replace
7018 // the second cast (CI). CSrc will then have a good chance of being dead.
7019 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007020 }
7021 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007022
Reid Spencer3da59db2006-11-27 01:05:10 +00007023 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007024 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7025 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7026 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007027
7028 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007029 if (isa<PHINode>(Src))
7030 if (Instruction *NV = FoldOpIntoPhi(CI))
7031 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007032
Reid Spencer3da59db2006-11-27 01:05:10 +00007033 return 0;
7034}
7035
Chris Lattnerd3e28342007-04-27 17:44:50 +00007036/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7037Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7038 Value *Src = CI.getOperand(0);
7039
Chris Lattnerd3e28342007-04-27 17:44:50 +00007040 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007041 // If casting the result of a getelementptr instruction with no offset, turn
7042 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007043 if (GEP->hasAllZeroIndices()) {
7044 // Changing the cast operand is usually not a good idea but it is safe
7045 // here because the pointer operand is being replaced with another
7046 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007047 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007048 CI.setOperand(0, GEP->getOperand(0));
7049 return &CI;
7050 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007051
7052 // If the GEP has a single use, and the base pointer is a bitcast, and the
7053 // GEP computes a constant offset, see if we can convert these three
7054 // instructions into fewer. This typically happens with unions and other
7055 // non-type-safe code.
7056 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7057 if (GEP->hasAllConstantIndices()) {
7058 // We are guaranteed to get a constant from EmitGEPOffset.
7059 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7060 int64_t Offset = OffsetV->getSExtValue();
7061
7062 // Get the base pointer input of the bitcast, and the type it points to.
7063 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7064 const Type *GEPIdxTy =
7065 cast<PointerType>(OrigBase->getType())->getElementType();
7066 if (GEPIdxTy->isSized()) {
7067 SmallVector<Value*, 8> NewIndices;
7068
Chris Lattnerc42e2262007-05-05 01:59:31 +00007069 // Start with the index over the outer type. Note that the type size
7070 // might be zero (even if the offset isn't zero) if the indexed type
7071 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007072 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007073 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007074 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007075 FirstIdx = Offset/TySize;
7076 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007077
Chris Lattnerc42e2262007-05-05 01:59:31 +00007078 // Handle silly modulus not returning values values [0..TySize).
7079 if (Offset < 0) {
7080 --FirstIdx;
7081 Offset += TySize;
7082 assert(Offset >= 0);
7083 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007084 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007085 }
7086
7087 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007088
7089 // Index into the types. If we fail, set OrigBase to null.
7090 while (Offset) {
7091 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7092 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007093 if (Offset < (int64_t)SL->getSizeInBytes()) {
7094 unsigned Elt = SL->getElementContainingOffset(Offset);
7095 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007096
Chris Lattner6b6aef82007-05-15 00:16:00 +00007097 Offset -= SL->getElementOffset(Elt);
7098 GEPIdxTy = STy->getElementType(Elt);
7099 } else {
7100 // Otherwise, we can't index into this, bail out.
7101 Offset = 0;
7102 OrigBase = 0;
7103 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007104 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7105 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007106 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007107 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7108 Offset %= EltSize;
7109 } else {
7110 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7111 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007112 GEPIdxTy = STy->getElementType();
7113 } else {
7114 // Otherwise, we can't index into this, bail out.
7115 Offset = 0;
7116 OrigBase = 0;
7117 }
7118 }
7119 if (OrigBase) {
7120 // If we were able to index down into an element, create the GEP
7121 // and bitcast the result. This eliminates one bitcast, potentially
7122 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007123 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7124 NewIndices.begin(),
7125 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007126 InsertNewInstBefore(NGEP, CI);
7127 NGEP->takeName(GEP);
7128
Chris Lattner9bc14642007-04-28 00:57:34 +00007129 if (isa<BitCastInst>(CI))
7130 return new BitCastInst(NGEP, CI.getType());
7131 assert(isa<PtrToIntInst>(CI));
7132 return new PtrToIntInst(NGEP, CI.getType());
7133 }
7134 }
7135 }
7136 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007137 }
7138
7139 return commonCastTransforms(CI);
7140}
7141
7142
7143
Chris Lattnerc739cd62007-03-03 05:27:34 +00007144/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7145/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007146/// cases.
7147/// @brief Implement the transforms common to CastInst with integer operands
7148Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7149 if (Instruction *Result = commonCastTransforms(CI))
7150 return Result;
7151
7152 Value *Src = CI.getOperand(0);
7153 const Type *SrcTy = Src->getType();
7154 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007155 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7156 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007157
Reid Spencer3da59db2006-11-27 01:05:10 +00007158 // See if we can simplify any instructions used by the LHS whose sole
7159 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007160 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7161 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007162 KnownZero, KnownOne))
7163 return &CI;
7164
7165 // If the source isn't an instruction or has more than one use then we
7166 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007167 Instruction *SrcI = dyn_cast<Instruction>(Src);
7168 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007169 return 0;
7170
Chris Lattnerc739cd62007-03-03 05:27:34 +00007171 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007172 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007173 if (!isa<BitCastInst>(CI) &&
7174 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007175 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007176 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007177 // eliminates the cast, so it is always a win. If this is a zero-extension,
7178 // we need to do an AND to maintain the clear top-part of the computation,
7179 // so we require that the input have eliminated at least one cast. If this
7180 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007181 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007182 bool DoXForm;
7183 switch (CI.getOpcode()) {
7184 default:
7185 // All the others use floating point so we shouldn't actually
7186 // get here because of the check above.
7187 assert(0 && "Unknown cast type");
7188 case Instruction::Trunc:
7189 DoXForm = true;
7190 break;
7191 case Instruction::ZExt:
7192 DoXForm = NumCastsRemoved >= 1;
7193 break;
7194 case Instruction::SExt:
7195 DoXForm = NumCastsRemoved >= 2;
7196 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007197 }
7198
7199 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007200 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7201 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007202 assert(Res->getType() == DestTy);
7203 switch (CI.getOpcode()) {
7204 default: assert(0 && "Unknown cast type!");
7205 case Instruction::Trunc:
7206 case Instruction::BitCast:
7207 // Just replace this cast with the result.
7208 return ReplaceInstUsesWith(CI, Res);
7209 case Instruction::ZExt: {
7210 // We need to emit an AND to clear the high bits.
7211 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007212 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7213 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00007214 return BinaryOperator::createAnd(Res, C);
7215 }
7216 case Instruction::SExt:
7217 // We need to emit a cast to truncate, then a cast to sext.
7218 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007219 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7220 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007221 }
7222 }
7223 }
7224
7225 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7226 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7227
7228 switch (SrcI->getOpcode()) {
7229 case Instruction::Add:
7230 case Instruction::Mul:
7231 case Instruction::And:
7232 case Instruction::Or:
7233 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007234 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007235 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7236 // Don't insert two casts if they cannot be eliminated. We allow
7237 // two casts to be inserted if the sizes are the same. This could
7238 // only be converting signedness, which is a noop.
7239 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007240 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7241 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007242 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007243 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7244 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7245 return BinaryOperator::create(
7246 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007247 }
7248 }
7249
7250 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7251 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7252 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007253 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007254 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007255 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007256 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7257 }
7258 break;
7259 case Instruction::SDiv:
7260 case Instruction::UDiv:
7261 case Instruction::SRem:
7262 case Instruction::URem:
7263 // If we are just changing the sign, rewrite.
7264 if (DestBitSize == SrcBitSize) {
7265 // Don't insert two casts if they cannot be eliminated. We allow
7266 // two casts to be inserted if the sizes are the same. This could
7267 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007268 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7269 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007270 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7271 Op0, DestTy, SrcI);
7272 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7273 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007274 return BinaryOperator::create(
7275 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7276 }
7277 }
7278 break;
7279
7280 case Instruction::Shl:
7281 // Allow changing the sign of the source operand. Do not allow
7282 // changing the size of the shift, UNLESS the shift amount is a
7283 // constant. We must not change variable sized shifts to a smaller
7284 // size, because it is undefined to shift more bits out than exist
7285 // in the value.
7286 if (DestBitSize == SrcBitSize ||
7287 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007288 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7289 Instruction::BitCast : Instruction::Trunc);
7290 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007291 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007292 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007293 }
7294 break;
7295 case Instruction::AShr:
7296 // If this is a signed shr, and if all bits shifted in are about to be
7297 // truncated off, turn it into an unsigned shr to allow greater
7298 // simplifications.
7299 if (DestBitSize < SrcBitSize &&
7300 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007301 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007302 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7303 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00007304 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007305 }
7306 }
7307 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007308 }
7309 return 0;
7310}
7311
Chris Lattner8a9f5712007-04-11 06:57:46 +00007312Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007313 if (Instruction *Result = commonIntCastTransforms(CI))
7314 return Result;
7315
7316 Value *Src = CI.getOperand(0);
7317 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007318 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7319 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007320
7321 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7322 switch (SrcI->getOpcode()) {
7323 default: break;
7324 case Instruction::LShr:
7325 // We can shrink lshr to something smaller if we know the bits shifted in
7326 // are already zeros.
7327 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007328 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007329
7330 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007331 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007332 Value* SrcIOp0 = SrcI->getOperand(0);
7333 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007334 if (ShAmt >= DestBitWidth) // All zeros.
7335 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7336
7337 // Okay, we can shrink this. Truncate the input, then return a new
7338 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007339 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7340 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7341 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007342 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007343 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007344 } else { // This is a variable shr.
7345
7346 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7347 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7348 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007349 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007350 Value *One = ConstantInt::get(SrcI->getType(), 1);
7351
Reid Spencer832254e2007-02-02 02:16:23 +00007352 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007353 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007354 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007355 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7356 SrcI->getOperand(0),
7357 "tmp"), CI);
7358 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007359 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007360 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007361 }
7362 break;
7363 }
7364 }
7365
7366 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007367}
7368
Evan Chengb98a10e2008-03-24 00:21:34 +00007369/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7370/// in order to eliminate the icmp.
7371Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7372 bool DoXform) {
7373 // If we are just checking for a icmp eq of a single bit and zext'ing it
7374 // to an integer, then shift the bit to the appropriate place and then
7375 // cast to integer to avoid the comparison.
7376 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7377 const APInt &Op1CV = Op1C->getValue();
7378
7379 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7380 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7381 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7382 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7383 if (!DoXform) return ICI;
7384
7385 Value *In = ICI->getOperand(0);
7386 Value *Sh = ConstantInt::get(In->getType(),
7387 In->getType()->getPrimitiveSizeInBits()-1);
7388 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7389 In->getName()+".lobit"),
7390 CI);
7391 if (In->getType() != CI.getType())
7392 In = CastInst::createIntegerCast(In, CI.getType(),
7393 false/*ZExt*/, "tmp", &CI);
7394
7395 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7396 Constant *One = ConstantInt::get(In->getType(), 1);
7397 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7398 In->getName()+".not"),
7399 CI);
7400 }
7401
7402 return ReplaceInstUsesWith(CI, In);
7403 }
7404
7405
7406
7407 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7408 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7409 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7410 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7411 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7412 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7413 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7414 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7415 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7416 // This only works for EQ and NE
7417 ICI->isEquality()) {
7418 // If Op1C some other power of two, convert:
7419 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7420 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7421 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7422 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7423
7424 APInt KnownZeroMask(~KnownZero);
7425 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7426 if (!DoXform) return ICI;
7427
7428 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7429 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7430 // (X&4) == 2 --> false
7431 // (X&4) != 2 --> true
7432 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7433 Res = ConstantExpr::getZExt(Res, CI.getType());
7434 return ReplaceInstUsesWith(CI, Res);
7435 }
7436
7437 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7438 Value *In = ICI->getOperand(0);
7439 if (ShiftAmt) {
7440 // Perform a logical shr by shiftamt.
7441 // Insert the shift to put the result in the low bit.
7442 In = InsertNewInstBefore(BinaryOperator::createLShr(In,
7443 ConstantInt::get(In->getType(), ShiftAmt),
7444 In->getName()+".lobit"), CI);
7445 }
7446
7447 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7448 Constant *One = ConstantInt::get(In->getType(), 1);
7449 In = BinaryOperator::createXor(In, One, "tmp");
7450 InsertNewInstBefore(cast<Instruction>(In), CI);
7451 }
7452
7453 if (CI.getType() == In->getType())
7454 return ReplaceInstUsesWith(CI, In);
7455 else
7456 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7457 }
7458 }
7459 }
7460
7461 return 0;
7462}
7463
Chris Lattner8a9f5712007-04-11 06:57:46 +00007464Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007465 // If one of the common conversion will work ..
7466 if (Instruction *Result = commonIntCastTransforms(CI))
7467 return Result;
7468
7469 Value *Src = CI.getOperand(0);
7470
7471 // If this is a cast of a cast
7472 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007473 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7474 // types and if the sizes are just right we can convert this into a logical
7475 // 'and' which will be much cheaper than the pair of casts.
7476 if (isa<TruncInst>(CSrc)) {
7477 // Get the sizes of the types involved
7478 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007479 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7480 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7481 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007482 // If we're actually extending zero bits and the trunc is a no-op
7483 if (MidSize < DstSize && SrcSize == DstSize) {
7484 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007485 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007486 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007487 Instruction *And =
7488 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7489 // Unfortunately, if the type changed, we need to cast it back.
7490 if (And->getType() != CI.getType()) {
7491 And->setName(CSrc->getName()+".mask");
7492 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007493 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007494 }
7495 return And;
7496 }
7497 }
7498 }
7499
Evan Chengb98a10e2008-03-24 00:21:34 +00007500 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7501 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007502
Evan Chengb98a10e2008-03-24 00:21:34 +00007503 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7504 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7505 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7506 // of the (zext icmp) will be transformed.
7507 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7508 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7509 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7510 (transformZExtICmp(LHS, CI, false) ||
7511 transformZExtICmp(RHS, CI, false))) {
7512 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7513 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7514 return BinaryOperator::create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007515 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007516 }
7517
Reid Spencer3da59db2006-11-27 01:05:10 +00007518 return 0;
7519}
7520
Chris Lattner8a9f5712007-04-11 06:57:46 +00007521Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007522 if (Instruction *I = commonIntCastTransforms(CI))
7523 return I;
7524
Chris Lattner8a9f5712007-04-11 06:57:46 +00007525 Value *Src = CI.getOperand(0);
7526
7527 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7528 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7529 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7530 // If we are just checking for a icmp eq of a single bit and zext'ing it
7531 // to an integer, then shift the bit to the appropriate place and then
7532 // cast to integer to avoid the comparison.
7533 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7534 const APInt &Op1CV = Op1C->getValue();
7535
7536 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7537 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7538 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7539 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7540 Value *In = ICI->getOperand(0);
7541 Value *Sh = ConstantInt::get(In->getType(),
7542 In->getType()->getPrimitiveSizeInBits()-1);
7543 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007544 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007545 CI);
7546 if (In->getType() != CI.getType())
7547 In = CastInst::createIntegerCast(In, CI.getType(),
7548 true/*SExt*/, "tmp", &CI);
7549
7550 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7551 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7552 In->getName()+".not"), CI);
7553
7554 return ReplaceInstUsesWith(CI, In);
7555 }
7556 }
7557 }
7558
Chris Lattnerba417832007-04-11 06:12:58 +00007559 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007560}
7561
Chris Lattnerb7530652008-01-27 05:29:54 +00007562/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7563/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007564static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007565 APFloat F = CFP->getValueAPF();
7566 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007567 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007568 return 0;
7569}
7570
7571/// LookThroughFPExtensions - If this is an fp extension instruction, look
7572/// through it until we get the source value.
7573static Value *LookThroughFPExtensions(Value *V) {
7574 if (Instruction *I = dyn_cast<Instruction>(V))
7575 if (I->getOpcode() == Instruction::FPExt)
7576 return LookThroughFPExtensions(I->getOperand(0));
7577
7578 // If this value is a constant, return the constant in the smallest FP type
7579 // that can accurately represent it. This allows us to turn
7580 // (float)((double)X+2.0) into x+2.0f.
7581 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7582 if (CFP->getType() == Type::PPC_FP128Ty)
7583 return V; // No constant folding of this.
7584 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007585 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007586 return V;
7587 if (CFP->getType() == Type::DoubleTy)
7588 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007589 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007590 return V;
7591 // Don't try to shrink to various long double types.
7592 }
7593
7594 return V;
7595}
7596
7597Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7598 if (Instruction *I = commonCastTransforms(CI))
7599 return I;
7600
7601 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7602 // smaller than the destination type, we can eliminate the truncate by doing
7603 // the add as the smaller type. This applies to add/sub/mul/div as well as
7604 // many builtins (sqrt, etc).
7605 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7606 if (OpI && OpI->hasOneUse()) {
7607 switch (OpI->getOpcode()) {
7608 default: break;
7609 case Instruction::Add:
7610 case Instruction::Sub:
7611 case Instruction::Mul:
7612 case Instruction::FDiv:
7613 case Instruction::FRem:
7614 const Type *SrcTy = OpI->getType();
7615 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7616 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7617 if (LHSTrunc->getType() != SrcTy &&
7618 RHSTrunc->getType() != SrcTy) {
7619 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7620 // If the source types were both smaller than the destination type of
7621 // the cast, do this xform.
7622 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7623 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7624 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7625 CI.getType(), CI);
7626 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7627 CI.getType(), CI);
7628 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7629 }
7630 }
7631 break;
7632 }
7633 }
7634 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007635}
7636
7637Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7638 return commonCastTransforms(CI);
7639}
7640
7641Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007642 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007643}
7644
7645Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007646 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007647}
7648
7649Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7650 return commonCastTransforms(CI);
7651}
7652
7653Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7654 return commonCastTransforms(CI);
7655}
7656
7657Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007658 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007659}
7660
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007661Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7662 if (Instruction *I = commonCastTransforms(CI))
7663 return I;
7664
7665 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7666 if (!DestPointee->isSized()) return 0;
7667
7668 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7669 ConstantInt *Cst;
7670 Value *X;
7671 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7672 m_ConstantInt(Cst)))) {
7673 // If the source and destination operands have the same type, see if this
7674 // is a single-index GEP.
7675 if (X->getType() == CI.getType()) {
7676 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007677 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007678
7679 // Convert the constant to intptr type.
7680 APInt Offset = Cst->getValue();
7681 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7682
7683 // If Offset is evenly divisible by Size, we can do this xform.
7684 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7685 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007686 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007687 }
7688 }
7689 // TODO: Could handle other cases, e.g. where add is indexing into field of
7690 // struct etc.
7691 } else if (CI.getOperand(0)->hasOneUse() &&
7692 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7693 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7694 // "inttoptr+GEP" instead of "add+intptr".
7695
7696 // Get the size of the pointee type.
7697 uint64_t Size = TD->getABITypeSize(DestPointee);
7698
7699 // Convert the constant to intptr type.
7700 APInt Offset = Cst->getValue();
7701 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7702
7703 // If Offset is evenly divisible by Size, we can do this xform.
7704 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7705 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7706
7707 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7708 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007709 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007710 }
7711 }
7712 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007713}
7714
Chris Lattnerd3e28342007-04-27 17:44:50 +00007715Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007716 // If the operands are integer typed then apply the integer transforms,
7717 // otherwise just apply the common ones.
7718 Value *Src = CI.getOperand(0);
7719 const Type *SrcTy = Src->getType();
7720 const Type *DestTy = CI.getType();
7721
Chris Lattner42a75512007-01-15 02:27:26 +00007722 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007723 if (Instruction *Result = commonIntCastTransforms(CI))
7724 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007725 } else if (isa<PointerType>(SrcTy)) {
7726 if (Instruction *I = commonPointerCastTransforms(CI))
7727 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007728 } else {
7729 if (Instruction *Result = commonCastTransforms(CI))
7730 return Result;
7731 }
7732
7733
7734 // Get rid of casts from one type to the same type. These are useless and can
7735 // be replaced by the operand.
7736 if (DestTy == Src->getType())
7737 return ReplaceInstUsesWith(CI, Src);
7738
Reid Spencer3da59db2006-11-27 01:05:10 +00007739 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007740 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7741 const Type *DstElTy = DstPTy->getElementType();
7742 const Type *SrcElTy = SrcPTy->getElementType();
7743
Nate Begeman83ad90a2008-03-31 00:22:16 +00007744 // If the address spaces don't match, don't eliminate the bitcast, which is
7745 // required for changing types.
7746 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7747 return 0;
7748
Chris Lattnerd3e28342007-04-27 17:44:50 +00007749 // If we are casting a malloc or alloca to a pointer to a type of the same
7750 // size, rewrite the allocation instruction to allocate the "right" type.
7751 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7752 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7753 return V;
7754
Chris Lattnerd717c182007-05-05 22:32:24 +00007755 // If the source and destination are pointers, and this cast is equivalent
7756 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007757 // This can enhance SROA and other transforms that want type-safe pointers.
7758 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7759 unsigned NumZeros = 0;
7760 while (SrcElTy != DstElTy &&
7761 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7762 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7763 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7764 ++NumZeros;
7765 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007766
Chris Lattnerd3e28342007-04-27 17:44:50 +00007767 // If we found a path from the src to dest, create the getelementptr now.
7768 if (SrcElTy == DstElTy) {
7769 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007770 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7771 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007772 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007773 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007774
Reid Spencer3da59db2006-11-27 01:05:10 +00007775 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7776 if (SVI->hasOneUse()) {
7777 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7778 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007779 if (isa<VectorType>(DestTy) &&
7780 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007781 SVI->getType()->getNumElements()) {
7782 CastInst *Tmp;
7783 // If either of the operands is a cast from CI.getType(), then
7784 // evaluating the shuffle in the casted destination's type will allow
7785 // us to eliminate at least one cast.
7786 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7787 Tmp->getOperand(0)->getType() == DestTy) ||
7788 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7789 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007790 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7791 SVI->getOperand(0), DestTy, &CI);
7792 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7793 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007794 // Return a new shuffle vector. Use the same element ID's, as we
7795 // know the vector types match #elts.
7796 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007797 }
7798 }
7799 }
7800 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007801 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007802}
7803
Chris Lattnere576b912004-04-09 23:46:01 +00007804/// GetSelectFoldableOperands - We want to turn code that looks like this:
7805/// %C = or %A, %B
7806/// %D = select %cond, %C, %A
7807/// into:
7808/// %C = select %cond, %B, 0
7809/// %D = or %A, %C
7810///
7811/// Assuming that the specified instruction is an operand to the select, return
7812/// a bitmask indicating which operands of this instruction are foldable if they
7813/// equal the other incoming value of the select.
7814///
7815static unsigned GetSelectFoldableOperands(Instruction *I) {
7816 switch (I->getOpcode()) {
7817 case Instruction::Add:
7818 case Instruction::Mul:
7819 case Instruction::And:
7820 case Instruction::Or:
7821 case Instruction::Xor:
7822 return 3; // Can fold through either operand.
7823 case Instruction::Sub: // Can only fold on the amount subtracted.
7824 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007825 case Instruction::LShr:
7826 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007827 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007828 default:
7829 return 0; // Cannot fold
7830 }
7831}
7832
7833/// GetSelectFoldableConstant - For the same transformation as the previous
7834/// function, return the identity constant that goes into the select.
7835static Constant *GetSelectFoldableConstant(Instruction *I) {
7836 switch (I->getOpcode()) {
7837 default: assert(0 && "This cannot happen!"); abort();
7838 case Instruction::Add:
7839 case Instruction::Sub:
7840 case Instruction::Or:
7841 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007842 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007843 case Instruction::LShr:
7844 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007845 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007846 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007847 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007848 case Instruction::Mul:
7849 return ConstantInt::get(I->getType(), 1);
7850 }
7851}
7852
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007853/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7854/// have the same opcode and only one use each. Try to simplify this.
7855Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7856 Instruction *FI) {
7857 if (TI->getNumOperands() == 1) {
7858 // If this is a non-volatile load or a cast from the same type,
7859 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007860 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007861 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7862 return 0;
7863 } else {
7864 return 0; // unknown unary op.
7865 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007866
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007867 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00007868 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7869 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007870 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007871 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7872 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007873 }
7874
Reid Spencer832254e2007-02-02 02:16:23 +00007875 // Only handle binary operators here.
7876 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007877 return 0;
7878
7879 // Figure out if the operations have any operands in common.
7880 Value *MatchOp, *OtherOpT, *OtherOpF;
7881 bool MatchIsOpZero;
7882 if (TI->getOperand(0) == FI->getOperand(0)) {
7883 MatchOp = TI->getOperand(0);
7884 OtherOpT = TI->getOperand(1);
7885 OtherOpF = FI->getOperand(1);
7886 MatchIsOpZero = true;
7887 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7888 MatchOp = TI->getOperand(1);
7889 OtherOpT = TI->getOperand(0);
7890 OtherOpF = FI->getOperand(0);
7891 MatchIsOpZero = false;
7892 } else if (!TI->isCommutative()) {
7893 return 0;
7894 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7895 MatchOp = TI->getOperand(0);
7896 OtherOpT = TI->getOperand(1);
7897 OtherOpF = FI->getOperand(0);
7898 MatchIsOpZero = true;
7899 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7900 MatchOp = TI->getOperand(1);
7901 OtherOpT = TI->getOperand(0);
7902 OtherOpF = FI->getOperand(1);
7903 MatchIsOpZero = true;
7904 } else {
7905 return 0;
7906 }
7907
7908 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00007909 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
7910 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007911 InsertNewInstBefore(NewSI, SI);
7912
7913 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7914 if (MatchIsOpZero)
7915 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7916 else
7917 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007918 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007919 assert(0 && "Shouldn't get here");
7920 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007921}
7922
Chris Lattner3d69f462004-03-12 05:52:32 +00007923Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007924 Value *CondVal = SI.getCondition();
7925 Value *TrueVal = SI.getTrueValue();
7926 Value *FalseVal = SI.getFalseValue();
7927
7928 // select true, X, Y -> X
7929 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007930 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007931 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007932
7933 // select C, X, X -> X
7934 if (TrueVal == FalseVal)
7935 return ReplaceInstUsesWith(SI, TrueVal);
7936
Chris Lattnere87597f2004-10-16 18:11:37 +00007937 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7938 return ReplaceInstUsesWith(SI, FalseVal);
7939 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7940 return ReplaceInstUsesWith(SI, TrueVal);
7941 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7942 if (isa<Constant>(TrueVal))
7943 return ReplaceInstUsesWith(SI, TrueVal);
7944 else
7945 return ReplaceInstUsesWith(SI, FalseVal);
7946 }
7947
Reid Spencer4fe16d62007-01-11 18:21:29 +00007948 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007949 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007950 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007951 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007952 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007953 } else {
7954 // Change: A = select B, false, C --> A = and !B, C
7955 Value *NotCond =
7956 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7957 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007958 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007959 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007960 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007961 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007962 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007963 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007964 } else {
7965 // Change: A = select B, C, true --> A = or !B, C
7966 Value *NotCond =
7967 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7968 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007969 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007970 }
7971 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007972
7973 // select a, b, a -> a&b
7974 // select a, a, b -> a|b
7975 if (CondVal == TrueVal)
7976 return BinaryOperator::createOr(CondVal, FalseVal);
7977 else if (CondVal == FalseVal)
7978 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007979 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007980
Chris Lattner2eefe512004-04-09 19:05:30 +00007981 // Selecting between two integer constants?
7982 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7983 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007984 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007985 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007986 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007987 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007988 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007989 Value *NotCond =
7990 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007991 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007992 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007993 }
Chris Lattnerba417832007-04-11 06:12:58 +00007994
7995 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007996
Reid Spencere4d87aa2006-12-23 06:05:41 +00007997 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007998
Reid Spencere4d87aa2006-12-23 06:05:41 +00007999 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008000 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008001 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008002 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008003 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008004 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008005 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008006 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008007 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8008 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
8009 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008010 InsertNewInstBefore(SRA, SI);
8011
Reid Spencer3da59db2006-11-27 01:05:10 +00008012 // Finally, convert to the type of the select RHS. We figure out
8013 // if this requires a SExt, Trunc or BitCast based on the sizes.
8014 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008015 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8016 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008017 if (SRASize < SISize)
8018 opc = Instruction::SExt;
8019 else if (SRASize > SISize)
8020 opc = Instruction::Trunc;
8021 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008022 }
8023 }
8024
8025
8026 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008027 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008028 // non-constant value, eliminate this whole mess. This corresponds to
8029 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008030 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008031 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008032 cast<Constant>(IC->getOperand(1))->isNullValue())
8033 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8034 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008035 isa<ConstantInt>(ICA->getOperand(1)) &&
8036 (ICA->getOperand(1) == TrueValC ||
8037 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008038 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8039 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008040 // know whether we have a icmp_ne or icmp_eq and whether the
8041 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008042 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008043 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008044 Value *V = ICA;
8045 if (ShouldNotVal)
8046 V = InsertNewInstBefore(BinaryOperator::create(
8047 Instruction::Xor, V, ICA->getOperand(1)), SI);
8048 return ReplaceInstUsesWith(SI, V);
8049 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008050 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008051 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008052
8053 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008054 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8055 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008056 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008057 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8058 // This is not safe in general for floating point:
8059 // consider X== -0, Y== +0.
8060 // It becomes safe if either operand is a nonzero constant.
8061 ConstantFP *CFPt, *CFPf;
8062 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8063 !CFPt->getValueAPF().isZero()) ||
8064 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8065 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008066 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008067 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008068 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008069 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008070 return ReplaceInstUsesWith(SI, TrueVal);
8071 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8072
Reid Spencere4d87aa2006-12-23 06:05:41 +00008073 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008074 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008075 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8076 // This is not safe in general for floating point:
8077 // consider X== -0, Y== +0.
8078 // It becomes safe if either operand is a nonzero constant.
8079 ConstantFP *CFPt, *CFPf;
8080 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8081 !CFPt->getValueAPF().isZero()) ||
8082 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8083 !CFPf->getValueAPF().isZero()))
8084 return ReplaceInstUsesWith(SI, FalseVal);
8085 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008086 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008087 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8088 return ReplaceInstUsesWith(SI, TrueVal);
8089 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8090 }
8091 }
8092
8093 // See if we are selecting two values based on a comparison of the two values.
8094 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8095 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8096 // Transform (X == Y) ? X : Y -> Y
8097 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8098 return ReplaceInstUsesWith(SI, FalseVal);
8099 // Transform (X != Y) ? X : Y -> X
8100 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8101 return ReplaceInstUsesWith(SI, TrueVal);
8102 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8103
8104 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8105 // Transform (X == Y) ? Y : X -> X
8106 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8107 return ReplaceInstUsesWith(SI, FalseVal);
8108 // Transform (X != Y) ? Y : X -> Y
8109 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008110 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008111 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8112 }
8113 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008114
Chris Lattner87875da2005-01-13 22:52:24 +00008115 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8116 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8117 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008118 Instruction *AddOp = 0, *SubOp = 0;
8119
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008120 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8121 if (TI->getOpcode() == FI->getOpcode())
8122 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8123 return IV;
8124
8125 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8126 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008127 if (TI->getOpcode() == Instruction::Sub &&
8128 FI->getOpcode() == Instruction::Add) {
8129 AddOp = FI; SubOp = TI;
8130 } else if (FI->getOpcode() == Instruction::Sub &&
8131 TI->getOpcode() == Instruction::Add) {
8132 AddOp = TI; SubOp = FI;
8133 }
8134
8135 if (AddOp) {
8136 Value *OtherAddOp = 0;
8137 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8138 OtherAddOp = AddOp->getOperand(1);
8139 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8140 OtherAddOp = AddOp->getOperand(0);
8141 }
8142
8143 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008144 // So at this point we know we have (Y -> OtherAddOp):
8145 // select C, (add X, Y), (sub X, Z)
8146 Value *NegVal; // Compute -Z
8147 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8148 NegVal = ConstantExpr::getNeg(C);
8149 } else {
8150 NegVal = InsertNewInstBefore(
8151 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008152 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008153
8154 Value *NewTrueOp = OtherAddOp;
8155 Value *NewFalseOp = NegVal;
8156 if (AddOp != TI)
8157 std::swap(NewTrueOp, NewFalseOp);
8158 Instruction *NewSel =
Gabor Greif051a9502008-04-06 20:25:17 +00008159 SelectInst::Create(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008160
8161 NewSel = InsertNewInstBefore(NewSel, SI);
8162 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008163 }
8164 }
8165 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008166
Chris Lattnere576b912004-04-09 23:46:01 +00008167 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008168 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008169 // See the comment above GetSelectFoldableOperands for a description of the
8170 // transformation we are doing here.
8171 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8172 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8173 !isa<Constant>(FalseVal))
8174 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8175 unsigned OpToFold = 0;
8176 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8177 OpToFold = 1;
8178 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8179 OpToFold = 2;
8180 }
8181
8182 if (OpToFold) {
8183 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008184 Instruction *NewSel =
Gabor Greif051a9502008-04-06 20:25:17 +00008185 SelectInst::Create(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008186 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008187 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008188 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8189 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008190 else {
8191 assert(0 && "Unknown instruction!!");
8192 }
8193 }
8194 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008195
Chris Lattnere576b912004-04-09 23:46:01 +00008196 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8197 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8198 !isa<Constant>(TrueVal))
8199 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8200 unsigned OpToFold = 0;
8201 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8202 OpToFold = 1;
8203 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8204 OpToFold = 2;
8205 }
8206
8207 if (OpToFold) {
8208 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008209 Instruction *NewSel =
Gabor Greif051a9502008-04-06 20:25:17 +00008210 SelectInst::Create(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008211 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008212 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008213 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8214 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008215 else
Chris Lattnere576b912004-04-09 23:46:01 +00008216 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008217 }
8218 }
8219 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008220
8221 if (BinaryOperator::isNot(CondVal)) {
8222 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8223 SI.setOperand(1, FalseVal);
8224 SI.setOperand(2, TrueVal);
8225 return &SI;
8226 }
8227
Chris Lattner3d69f462004-03-12 05:52:32 +00008228 return 0;
8229}
8230
Dan Gohmaneee962e2008-04-10 18:43:06 +00008231/// EnforceKnownAlignment - If the specified pointer points to an object that
8232/// we control, modify the object's alignment to PrefAlign. This isn't
8233/// often possible though. If alignment is important, a more reliable approach
8234/// is to simply align all global variables and allocation instructions to
8235/// their preferred alignment from the beginning.
8236///
8237static unsigned EnforceKnownAlignment(Value *V,
8238 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008239
Dan Gohmaneee962e2008-04-10 18:43:06 +00008240 User *U = dyn_cast<User>(V);
8241 if (!U) return Align;
8242
8243 switch (getOpcode(U)) {
8244 default: break;
8245 case Instruction::BitCast:
8246 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8247 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008248 // If all indexes are zero, it is just the alignment of the base pointer.
8249 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008250 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8251 if (!isa<Constant>(U->getOperand(i)) ||
8252 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008253 AllZeroOperands = false;
8254 break;
8255 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008256
8257 if (AllZeroOperands) {
8258 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008259 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008260 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008261 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008262 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008263 }
8264
8265 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8266 // If there is a large requested alignment and we can, bump up the alignment
8267 // of the global.
8268 if (!GV->isDeclaration()) {
8269 GV->setAlignment(PrefAlign);
8270 Align = PrefAlign;
8271 }
8272 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8273 // If there is a requested alignment and if this is an alloca, round up. We
8274 // don't do this for malloc, because some systems can't respect the request.
8275 if (isa<AllocaInst>(AI)) {
8276 AI->setAlignment(PrefAlign);
8277 Align = PrefAlign;
8278 }
8279 }
8280
8281 return Align;
8282}
8283
8284/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8285/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8286/// and it is more than the alignment of the ultimate object, see if we can
8287/// increase the alignment of the ultimate object, making this check succeed.
8288unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8289 unsigned PrefAlign) {
8290 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8291 sizeof(PrefAlign) * CHAR_BIT;
8292 APInt Mask = APInt::getAllOnesValue(BitWidth);
8293 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8294 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8295 unsigned TrailZ = KnownZero.countTrailingOnes();
8296 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8297
8298 if (PrefAlign > Align)
8299 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8300
8301 // We don't need to make any adjustment.
8302 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008303}
8304
Chris Lattnerf497b022008-01-13 23:50:23 +00008305Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008306 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8307 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008308 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8309 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8310
8311 if (CopyAlign < MinAlign) {
8312 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8313 return MI;
8314 }
8315
8316 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8317 // load/store.
8318 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8319 if (MemOpLength == 0) return 0;
8320
Chris Lattner37ac6082008-01-14 00:28:35 +00008321 // Source and destination pointer types are always "i8*" for intrinsic. See
8322 // if the size is something we can handle with a single primitive load/store.
8323 // A single load+store correctly handles overlapping memory in the memmove
8324 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008325 unsigned Size = MemOpLength->getZExtValue();
8326 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008327 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008328
Chris Lattner37ac6082008-01-14 00:28:35 +00008329 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008330 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008331
8332 // Memcpy forces the use of i8* for the source and destination. That means
8333 // that if you're using memcpy to move one double around, you'll get a cast
8334 // from double* to i8*. We'd much rather use a double load+store rather than
8335 // an i64 load+store, here because this improves the odds that the source or
8336 // dest address will be promotable. See if we can find a better type than the
8337 // integer datatype.
8338 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8339 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8340 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8341 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8342 // down through these levels if so.
8343 while (!SrcETy->isFirstClassType()) {
8344 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8345 if (STy->getNumElements() == 1)
8346 SrcETy = STy->getElementType(0);
8347 else
8348 break;
8349 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8350 if (ATy->getNumElements() == 1)
8351 SrcETy = ATy->getElementType();
8352 else
8353 break;
8354 } else
8355 break;
8356 }
8357
8358 if (SrcETy->isFirstClassType())
8359 NewPtrTy = PointerType::getUnqual(SrcETy);
8360 }
8361 }
8362
8363
Chris Lattnerf497b022008-01-13 23:50:23 +00008364 // If the memcpy/memmove provides better alignment info than we can
8365 // infer, use it.
8366 SrcAlign = std::max(SrcAlign, CopyAlign);
8367 DstAlign = std::max(DstAlign, CopyAlign);
8368
8369 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8370 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008371 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8372 InsertNewInstBefore(L, *MI);
8373 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8374
8375 // Set the size of the copy to 0, it will be deleted on the next iteration.
8376 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8377 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008378}
Chris Lattner3d69f462004-03-12 05:52:32 +00008379
Chris Lattner8b0ea312006-01-13 20:11:04 +00008380/// visitCallInst - CallInst simplification. This mostly only handles folding
8381/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8382/// the heavy lifting.
8383///
Chris Lattner9fe38862003-06-19 17:00:31 +00008384Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008385 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8386 if (!II) return visitCallSite(&CI);
8387
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008388 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8389 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008390 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008391 bool Changed = false;
8392
8393 // memmove/cpy/set of zero bytes is a noop.
8394 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8395 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8396
Chris Lattner35b9e482004-10-12 04:52:52 +00008397 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008398 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008399 // Replace the instruction with just byte operations. We would
8400 // transform other cases to loads/stores, but we don't know if
8401 // alignment is sufficient.
8402 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008403 }
8404
Chris Lattner35b9e482004-10-12 04:52:52 +00008405 // If we have a memmove and the source operation is a constant global,
8406 // then the source and dest pointers can't alias, so we can change this
8407 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008408 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008409 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8410 if (GVSrc->isConstant()) {
8411 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008412 Intrinsic::ID MemCpyID;
8413 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8414 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008415 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008416 MemCpyID = Intrinsic::memcpy_i64;
8417 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008418 Changed = true;
8419 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008420 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008421
Chris Lattner95a959d2006-03-06 20:18:44 +00008422 // If we can determine a pointer alignment that is bigger than currently
8423 // set, update the alignment.
8424 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008425 if (Instruction *I = SimplifyMemTransfer(MI))
8426 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008427 } else if (isa<MemSetInst>(MI)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008428 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Reid Spencerb83eb642006-10-20 07:07:24 +00008429 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008430 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00008431 Changed = true;
8432 }
8433 }
8434
Chris Lattner8b0ea312006-01-13 20:11:04 +00008435 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008436 } else {
8437 switch (II->getIntrinsicID()) {
8438 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008439 case Intrinsic::ppc_altivec_lvx:
8440 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008441 case Intrinsic::x86_sse_loadu_ps:
8442 case Intrinsic::x86_sse2_loadu_pd:
8443 case Intrinsic::x86_sse2_loadu_dq:
8444 // Turn PPC lvx -> load if the pointer is known aligned.
8445 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008446 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008447 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8448 PointerType::getUnqual(II->getType()),
8449 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008450 return new LoadInst(Ptr);
8451 }
8452 break;
8453 case Intrinsic::ppc_altivec_stvx:
8454 case Intrinsic::ppc_altivec_stvxl:
8455 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008456 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008457 const Type *OpPtrTy =
8458 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008459 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008460 return new StoreInst(II->getOperand(1), Ptr);
8461 }
8462 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008463 case Intrinsic::x86_sse_storeu_ps:
8464 case Intrinsic::x86_sse2_storeu_pd:
8465 case Intrinsic::x86_sse2_storeu_dq:
8466 case Intrinsic::x86_sse2_storel_dq:
8467 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008468 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008469 const Type *OpPtrTy =
8470 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008471 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008472 return new StoreInst(II->getOperand(2), Ptr);
8473 }
8474 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008475
8476 case Intrinsic::x86_sse_cvttss2si: {
8477 // These intrinsics only demands the 0th element of its input vector. If
8478 // we can simplify the input based on that, do so now.
8479 uint64_t UndefElts;
8480 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8481 UndefElts)) {
8482 II->setOperand(1, V);
8483 return II;
8484 }
8485 break;
8486 }
8487
Chris Lattnere2ed0572006-04-06 19:19:17 +00008488 case Intrinsic::ppc_altivec_vperm:
8489 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008490 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008491 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8492
8493 // Check that all of the elements are integer constants or undefs.
8494 bool AllEltsOk = true;
8495 for (unsigned i = 0; i != 16; ++i) {
8496 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8497 !isa<UndefValue>(Mask->getOperand(i))) {
8498 AllEltsOk = false;
8499 break;
8500 }
8501 }
8502
8503 if (AllEltsOk) {
8504 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008505 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8506 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008507 Value *Result = UndefValue::get(Op0->getType());
8508
8509 // Only extract each element once.
8510 Value *ExtractedElts[32];
8511 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8512
8513 for (unsigned i = 0; i != 16; ++i) {
8514 if (isa<UndefValue>(Mask->getOperand(i)))
8515 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008516 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008517 Idx &= 31; // Match the hardware behavior.
8518
8519 if (ExtractedElts[Idx] == 0) {
8520 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008521 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008522 InsertNewInstBefore(Elt, CI);
8523 ExtractedElts[Idx] = Elt;
8524 }
8525
8526 // Insert this value into the result vector.
Gabor Greif051a9502008-04-06 20:25:17 +00008527 Result = InsertElementInst::Create(Result, ExtractedElts[Idx], i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008528 InsertNewInstBefore(cast<Instruction>(Result), CI);
8529 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008530 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008531 }
8532 }
8533 break;
8534
Chris Lattnera728ddc2006-01-13 21:28:09 +00008535 case Intrinsic::stackrestore: {
8536 // If the save is right next to the restore, remove the restore. This can
8537 // happen when variable allocas are DCE'd.
8538 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8539 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8540 BasicBlock::iterator BI = SS;
8541 if (&*++BI == II)
8542 return EraseInstFromFunction(CI);
8543 }
8544 }
8545
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008546 // Scan down this block to see if there is another stack restore in the
8547 // same block without an intervening call/alloca.
8548 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008549 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008550 bool CannotRemove = false;
8551 for (++BI; &*BI != TI; ++BI) {
8552 if (isa<AllocaInst>(BI)) {
8553 CannotRemove = true;
8554 break;
8555 }
8556 if (isa<CallInst>(BI)) {
8557 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008558 CannotRemove = true;
8559 break;
8560 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008561 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008562 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008563 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008564 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008565
8566 // If the stack restore is in a return/unwind block and if there are no
8567 // allocas or calls between the restore and the return, nuke the restore.
8568 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8569 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008570 break;
8571 }
8572 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008573 }
8574
Chris Lattner8b0ea312006-01-13 20:11:04 +00008575 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008576}
8577
8578// InvokeInst simplification
8579//
8580Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008581 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008582}
8583
Chris Lattnera44d8a22003-10-07 22:32:43 +00008584// visitCallSite - Improvements for call and invoke instructions.
8585//
8586Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008587 bool Changed = false;
8588
8589 // If the callee is a constexpr cast of a function, attempt to move the cast
8590 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008591 if (transformConstExprCastCall(CS)) return 0;
8592
Chris Lattner6c266db2003-10-07 22:54:13 +00008593 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008594
Chris Lattner08b22ec2005-05-13 07:09:09 +00008595 if (Function *CalleeF = dyn_cast<Function>(Callee))
8596 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8597 Instruction *OldCall = CS.getInstruction();
8598 // If the call and callee calling conventions don't match, this call must
8599 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008600 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008601 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8602 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008603 if (!OldCall->use_empty())
8604 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8605 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8606 return EraseInstFromFunction(*OldCall);
8607 return 0;
8608 }
8609
Chris Lattner17be6352004-10-18 02:59:09 +00008610 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8611 // This instruction is not reachable, just remove it. We insert a store to
8612 // undef so that we know that this code is not reachable, despite the fact
8613 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008614 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008615 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008616 CS.getInstruction());
8617
8618 if (!CS.getInstruction()->use_empty())
8619 CS.getInstruction()->
8620 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8621
8622 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8623 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008624 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8625 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008626 }
Chris Lattner17be6352004-10-18 02:59:09 +00008627 return EraseInstFromFunction(*CS.getInstruction());
8628 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008629
Duncan Sandscdb6d922007-09-17 10:26:40 +00008630 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8631 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8632 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8633 return transformCallThroughTrampoline(CS);
8634
Chris Lattner6c266db2003-10-07 22:54:13 +00008635 const PointerType *PTy = cast<PointerType>(Callee->getType());
8636 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8637 if (FTy->isVarArg()) {
8638 // See if we can optimize any arguments passed through the varargs area of
8639 // the call.
8640 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8641 E = CS.arg_end(); I != E; ++I)
8642 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8643 // If this cast does not effect the value passed through the varargs
8644 // area, we can eliminate the use of the cast.
8645 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008646 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008647 *I = Op;
8648 Changed = true;
8649 }
8650 }
8651 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008652
Duncan Sandsf0c33542007-12-19 21:13:37 +00008653 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008654 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008655 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008656 Changed = true;
8657 }
8658
Chris Lattner6c266db2003-10-07 22:54:13 +00008659 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008660}
8661
Chris Lattner9fe38862003-06-19 17:00:31 +00008662// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8663// attempt to move the cast to the arguments of the call/invoke.
8664//
8665bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8666 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8667 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008668 if (CE->getOpcode() != Instruction::BitCast ||
8669 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008670 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008671 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008672 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008673 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008674
8675 // Okay, this is a cast from a function to a different type. Unless doing so
8676 // would cause a type conversion of one of our arguments, change this call to
8677 // be a direct call with arguments casted to the appropriate types.
8678 //
8679 const FunctionType *FT = Callee->getFunctionType();
8680 const Type *OldRetTy = Caller->getType();
8681
Devang Patel75e6f022008-03-11 18:04:06 +00008682 if (isa<StructType>(FT->getReturnType()))
8683 return false; // TODO: Handle multiple return values.
8684
Chris Lattnerf78616b2004-01-14 06:06:08 +00008685 // Check to see if we are changing the return type...
8686 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008687 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008688 // Conversion is ok if changing from pointer to int of same size.
8689 !(isa<PointerType>(FT->getReturnType()) &&
8690 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008691 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008692
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008693 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008694 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008695 FT->getReturnType() != Type::VoidTy &&
8696 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008697 return false; // Cannot transform this return value.
8698
Chris Lattner58d74912008-03-12 17:45:29 +00008699 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8700 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008701 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8702 return false; // Attribute not compatible with transformed value.
8703 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008704
Chris Lattnerf78616b2004-01-14 06:06:08 +00008705 // If the callsite is an invoke instruction, and the return value is used by
8706 // a PHI node in a successor, we cannot change the return type of the call
8707 // because there is no place to put the cast instruction (without breaking
8708 // the critical edge). Bail out in this case.
8709 if (!Caller->use_empty())
8710 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8711 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8712 UI != E; ++UI)
8713 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8714 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008715 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008716 return false;
8717 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008718
8719 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8720 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008721
Chris Lattner9fe38862003-06-19 17:00:31 +00008722 CallSite::arg_iterator AI = CS.arg_begin();
8723 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8724 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008725 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008726
8727 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008728 return false; // Cannot transform this parameter value.
8729
Chris Lattner58d74912008-03-12 17:45:29 +00008730 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8731 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008732
Reid Spencer3da59db2006-11-27 01:05:10 +00008733 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008734 // Some conversions are safe even if we do not have a body.
8735 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008736 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008737 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008738 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008739 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8740 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008741 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008742 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008743 }
8744
8745 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008746 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008747 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008748
Chris Lattner58d74912008-03-12 17:45:29 +00008749 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8750 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008751 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008752 // won't be dropping them. Check that these extra arguments have attributes
8753 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008754 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8755 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008756 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008757 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008758 if (PAttrs & ParamAttr::VarArgsIncompatible)
8759 return false;
8760 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008761
Chris Lattner9fe38862003-06-19 17:00:31 +00008762 // Okay, we decided that this is a safe thing to do: go ahead and start
8763 // inserting cast instructions as necessary...
8764 std::vector<Value*> Args;
8765 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008766 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008767 attrVec.reserve(NumCommonArgs);
8768
8769 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008770 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008771
8772 // If the return value is not being used, the type may not be compatible
8773 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008774 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008775
8776 // Add the new return attributes.
8777 if (RAttrs)
8778 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008779
8780 AI = CS.arg_begin();
8781 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8782 const Type *ParamTy = FT->getParamType(i);
8783 if ((*AI)->getType() == ParamTy) {
8784 Args.push_back(*AI);
8785 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008786 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008787 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008788 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008789 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008790 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008791
8792 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008793 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008794 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008795 }
8796
8797 // If the function takes more arguments than the call was taking, add them
8798 // now...
8799 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8800 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8801
8802 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008803 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008804 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008805 cerr << "WARNING: While resolving call to function '"
8806 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008807 } else {
8808 // Add all of the arguments in their promoted form to the arg list...
8809 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8810 const Type *PTy = getPromotedType((*AI)->getType());
8811 if (PTy != (*AI)->getType()) {
8812 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008813 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8814 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008815 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008816 InsertNewInstBefore(Cast, *Caller);
8817 Args.push_back(Cast);
8818 } else {
8819 Args.push_back(*AI);
8820 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008821
Duncan Sandse1e520f2008-01-13 08:02:44 +00008822 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008823 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00008824 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8825 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008826 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008827 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008828
8829 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008830 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008831
Chris Lattner58d74912008-03-12 17:45:29 +00008832 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008833
Chris Lattner9fe38862003-06-19 17:00:31 +00008834 Instruction *NC;
8835 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00008836 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
8837 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008838 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008839 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008840 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00008841 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
8842 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008843 CallInst *CI = cast<CallInst>(Caller);
8844 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008845 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008846 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008847 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008848 }
8849
Chris Lattner6934a042007-02-11 01:23:03 +00008850 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008851 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008852 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008853 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008854 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008855 OldRetTy, false);
8856 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008857
8858 // If this is an invoke instruction, we should insert it after the first
8859 // non-phi, instruction in the normal successor block.
8860 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8861 BasicBlock::iterator I = II->getNormalDest()->begin();
8862 while (isa<PHINode>(I)) ++I;
8863 InsertNewInstBefore(NC, *I);
8864 } else {
8865 // Otherwise, it's a call, just insert cast right after the call instr
8866 InsertNewInstBefore(NC, *Caller);
8867 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008868 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008869 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008870 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008871 }
8872 }
8873
8874 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8875 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008876 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008877 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008878 return true;
8879}
8880
Duncan Sandscdb6d922007-09-17 10:26:40 +00008881// transformCallThroughTrampoline - Turn a call to a function created by the
8882// init_trampoline intrinsic into a direct call to the underlying function.
8883//
8884Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8885 Value *Callee = CS.getCalledValue();
8886 const PointerType *PTy = cast<PointerType>(Callee->getType());
8887 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00008888 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008889
8890 // If the call already has the 'nest' attribute somewhere then give up -
8891 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00008892 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008893 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008894
8895 IntrinsicInst *Tramp =
8896 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8897
8898 Function *NestF =
8899 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8900 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8901 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8902
Chris Lattner58d74912008-03-12 17:45:29 +00008903 const PAListPtr &NestAttrs = NestF->getParamAttrs();
8904 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008905 unsigned NestIdx = 1;
8906 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008907 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008908
8909 // Look for a parameter marked with the 'nest' attribute.
8910 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8911 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00008912 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008913 // Record the parameter type and any other attributes.
8914 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00008915 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008916 break;
8917 }
8918
8919 if (NestTy) {
8920 Instruction *Caller = CS.getInstruction();
8921 std::vector<Value*> NewArgs;
8922 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8923
Chris Lattner58d74912008-03-12 17:45:29 +00008924 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
8925 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008926
Duncan Sandscdb6d922007-09-17 10:26:40 +00008927 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008928 // mean appending it. Likewise for attributes.
8929
8930 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008931 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
8932 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008933
Duncan Sandscdb6d922007-09-17 10:26:40 +00008934 {
8935 unsigned Idx = 1;
8936 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8937 do {
8938 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008939 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008940 Value *NestVal = Tramp->getOperand(3);
8941 if (NestVal->getType() != NestTy)
8942 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8943 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008944 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008945 }
8946
8947 if (I == E)
8948 break;
8949
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008950 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008951 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00008952 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008953 NewAttrs.push_back
8954 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008955
8956 ++Idx, ++I;
8957 } while (1);
8958 }
8959
8960 // The trampoline may have been bitcast to a bogus type (FTy).
8961 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008962 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008963
Duncan Sandscdb6d922007-09-17 10:26:40 +00008964 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008965 NewTypes.reserve(FTy->getNumParams()+1);
8966
Duncan Sandscdb6d922007-09-17 10:26:40 +00008967 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008968 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008969 {
8970 unsigned Idx = 1;
8971 FunctionType::param_iterator I = FTy->param_begin(),
8972 E = FTy->param_end();
8973
8974 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008975 if (Idx == NestIdx)
8976 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008977 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008978
8979 if (I == E)
8980 break;
8981
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008982 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008983 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008984
8985 ++Idx, ++I;
8986 } while (1);
8987 }
8988
8989 // Replace the trampoline call with a direct call. Let the generic
8990 // code sort out any function type mismatches.
8991 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008992 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008993 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8994 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00008995 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00008996
8997 Instruction *NewCaller;
8998 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00008999 NewCaller = InvokeInst::Create(NewCallee,
9000 II->getNormalDest(), II->getUnwindDest(),
9001 NewArgs.begin(), NewArgs.end(),
9002 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009003 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009004 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009005 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009006 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9007 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009008 if (cast<CallInst>(Caller)->isTailCall())
9009 cast<CallInst>(NewCaller)->setTailCall();
9010 cast<CallInst>(NewCaller)->
9011 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009012 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009013 }
9014 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9015 Caller->replaceAllUsesWith(NewCaller);
9016 Caller->eraseFromParent();
9017 RemoveFromWorkList(Caller);
9018 return 0;
9019 }
9020 }
9021
9022 // Replace the trampoline call with a direct call. Since there is no 'nest'
9023 // parameter, there is no need to adjust the argument list. Let the generic
9024 // code sort out any function type mismatches.
9025 Constant *NewCallee =
9026 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9027 CS.setCalledFunction(NewCallee);
9028 return CS.getInstruction();
9029}
9030
Chris Lattner7da52b22006-11-01 04:51:18 +00009031/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9032/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9033/// and a single binop.
9034Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9035 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009036 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9037 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009038 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009039 Value *LHSVal = FirstInst->getOperand(0);
9040 Value *RHSVal = FirstInst->getOperand(1);
9041
9042 const Type *LHSType = LHSVal->getType();
9043 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009044
9045 // Scan to see if all operands are the same opcode, all have one use, and all
9046 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009047 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009048 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009049 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009050 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009051 // types or GEP's with different index types.
9052 I->getOperand(0)->getType() != LHSType ||
9053 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009054 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009055
9056 // If they are CmpInst instructions, check their predicates
9057 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9058 if (cast<CmpInst>(I)->getPredicate() !=
9059 cast<CmpInst>(FirstInst)->getPredicate())
9060 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009061
9062 // Keep track of which operand needs a phi node.
9063 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9064 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009065 }
9066
Chris Lattner53738a42006-11-08 19:42:28 +00009067 // Otherwise, this is safe to transform, determine if it is profitable.
9068
9069 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9070 // Indexes are often folded into load/store instructions, so we don't want to
9071 // hide them behind a phi.
9072 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9073 return 0;
9074
Chris Lattner7da52b22006-11-01 04:51:18 +00009075 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009076 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009077 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009078 if (LHSVal == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00009079 NewLHS = PHINode::Create(LHSType, FirstInst->getOperand(0)->getName()+".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009080 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9081 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009082 InsertNewInstBefore(NewLHS, PN);
9083 LHSVal = NewLHS;
9084 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009085
9086 if (RHSVal == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00009087 NewRHS = PHINode::Create(RHSType, FirstInst->getOperand(1)->getName()+".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009088 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9089 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009090 InsertNewInstBefore(NewRHS, PN);
9091 RHSVal = NewRHS;
9092 }
9093
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009094 // Add all operands to the new PHIs.
9095 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9096 if (NewLHS) {
9097 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9098 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9099 }
9100 if (NewRHS) {
9101 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9102 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9103 }
9104 }
9105
Chris Lattner7da52b22006-11-01 04:51:18 +00009106 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00009107 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009108 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9109 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
9110 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009111 else {
9112 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009113 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009114 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009115}
9116
Chris Lattner76c73142006-11-01 07:13:54 +00009117/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9118/// of the block that defines it. This means that it must be obvious the value
9119/// of the load is not changed from the point of the load to the end of the
9120/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009121///
9122/// Finally, it is safe, but not profitable, to sink a load targetting a
9123/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9124/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009125static bool isSafeToSinkLoad(LoadInst *L) {
9126 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9127
9128 for (++BBI; BBI != E; ++BBI)
9129 if (BBI->mayWriteToMemory())
9130 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009131
9132 // Check for non-address taken alloca. If not address-taken already, it isn't
9133 // profitable to do this xform.
9134 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9135 bool isAddressTaken = false;
9136 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9137 UI != E; ++UI) {
9138 if (isa<LoadInst>(UI)) continue;
9139 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9140 // If storing TO the alloca, then the address isn't taken.
9141 if (SI->getOperand(1) == AI) continue;
9142 }
9143 isAddressTaken = true;
9144 break;
9145 }
9146
9147 if (!isAddressTaken)
9148 return false;
9149 }
9150
Chris Lattner76c73142006-11-01 07:13:54 +00009151 return true;
9152}
9153
Chris Lattner9fe38862003-06-19 17:00:31 +00009154
Chris Lattnerbac32862004-11-14 19:13:23 +00009155// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9156// operator and they all are only used by the PHI, PHI together their
9157// inputs, and do the operation once, to the result of the PHI.
9158Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9159 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9160
9161 // Scan the instruction, looking for input operations that can be folded away.
9162 // If all input operands to the phi are the same instruction (e.g. a cast from
9163 // the same type or "+42") we can pull the operation through the PHI, reducing
9164 // code size and simplifying code.
9165 Constant *ConstantOp = 0;
9166 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009167 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009168 if (isa<CastInst>(FirstInst)) {
9169 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009170 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009171 // Can fold binop, compare or shift here if the RHS is a constant,
9172 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009173 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009174 if (ConstantOp == 0)
9175 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009176 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9177 isVolatile = LI->isVolatile();
9178 // We can't sink the load if the loaded value could be modified between the
9179 // load and the PHI.
9180 if (LI->getParent() != PN.getIncomingBlock(0) ||
9181 !isSafeToSinkLoad(LI))
9182 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009183 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009184 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009185 return FoldPHIArgBinOpIntoPHI(PN);
9186 // Can't handle general GEPs yet.
9187 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009188 } else {
9189 return 0; // Cannot fold this operation.
9190 }
9191
9192 // Check to see if all arguments are the same operation.
9193 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9194 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9195 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009196 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009197 return 0;
9198 if (CastSrcTy) {
9199 if (I->getOperand(0)->getType() != CastSrcTy)
9200 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009201 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009202 // We can't sink the load if the loaded value could be modified between
9203 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009204 if (LI->isVolatile() != isVolatile ||
9205 LI->getParent() != PN.getIncomingBlock(i) ||
9206 !isSafeToSinkLoad(LI))
9207 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009208 } else if (I->getOperand(1) != ConstantOp) {
9209 return 0;
9210 }
9211 }
9212
9213 // Okay, they are all the same operation. Create a new PHI node of the
9214 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009215 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9216 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009217 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009218
9219 Value *InVal = FirstInst->getOperand(0);
9220 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009221
9222 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009223 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9224 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9225 if (NewInVal != InVal)
9226 InVal = 0;
9227 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9228 }
9229
9230 Value *PhiVal;
9231 if (InVal) {
9232 // The new PHI unions all of the same values together. This is really
9233 // common, so we handle it intelligently here for compile-time speed.
9234 PhiVal = InVal;
9235 delete NewPN;
9236 } else {
9237 InsertNewInstBefore(NewPN, PN);
9238 PhiVal = NewPN;
9239 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009240
Chris Lattnerbac32862004-11-14 19:13:23 +00009241 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009242 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9243 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00009244 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00009245 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009246 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00009247 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009248 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9249 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
9250 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00009251 else
Reid Spencer832254e2007-02-02 02:16:23 +00009252 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00009253 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009254}
Chris Lattnera1be5662002-05-02 17:06:02 +00009255
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009256/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9257/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009258static bool DeadPHICycle(PHINode *PN,
9259 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009260 if (PN->use_empty()) return true;
9261 if (!PN->hasOneUse()) return false;
9262
9263 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009264 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009265 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009266
9267 // Don't scan crazily complex things.
9268 if (PotentiallyDeadPHIs.size() == 16)
9269 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009270
9271 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9272 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009273
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009274 return false;
9275}
9276
Chris Lattnercf5008a2007-11-06 21:52:06 +00009277/// PHIsEqualValue - Return true if this phi node is always equal to
9278/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9279/// z = some value; x = phi (y, z); y = phi (x, z)
9280static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9281 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9282 // See if we already saw this PHI node.
9283 if (!ValueEqualPHIs.insert(PN))
9284 return true;
9285
9286 // Don't scan crazily complex things.
9287 if (ValueEqualPHIs.size() == 16)
9288 return false;
9289
9290 // Scan the operands to see if they are either phi nodes or are equal to
9291 // the value.
9292 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9293 Value *Op = PN->getIncomingValue(i);
9294 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9295 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9296 return false;
9297 } else if (Op != NonPhiInVal)
9298 return false;
9299 }
9300
9301 return true;
9302}
9303
9304
Chris Lattner473945d2002-05-06 18:06:38 +00009305// PHINode simplification
9306//
Chris Lattner7e708292002-06-25 16:13:24 +00009307Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009308 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009309 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009310
Owen Anderson7e057142006-07-10 22:03:18 +00009311 if (Value *V = PN.hasConstantValue())
9312 return ReplaceInstUsesWith(PN, V);
9313
Owen Anderson7e057142006-07-10 22:03:18 +00009314 // If all PHI operands are the same operation, pull them through the PHI,
9315 // reducing code size.
9316 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9317 PN.getIncomingValue(0)->hasOneUse())
9318 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9319 return Result;
9320
9321 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9322 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9323 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009324 if (PN.hasOneUse()) {
9325 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9326 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009327 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009328 PotentiallyDeadPHIs.insert(&PN);
9329 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9330 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9331 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009332
9333 // If this phi has a single use, and if that use just computes a value for
9334 // the next iteration of a loop, delete the phi. This occurs with unused
9335 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9336 // common case here is good because the only other things that catch this
9337 // are induction variable analysis (sometimes) and ADCE, which is only run
9338 // late.
9339 if (PHIUser->hasOneUse() &&
9340 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9341 PHIUser->use_back() == &PN) {
9342 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9343 }
9344 }
Owen Anderson7e057142006-07-10 22:03:18 +00009345
Chris Lattnercf5008a2007-11-06 21:52:06 +00009346 // We sometimes end up with phi cycles that non-obviously end up being the
9347 // same value, for example:
9348 // z = some value; x = phi (y, z); y = phi (x, z)
9349 // where the phi nodes don't necessarily need to be in the same block. Do a
9350 // quick check to see if the PHI node only contains a single non-phi value, if
9351 // so, scan to see if the phi cycle is actually equal to that value.
9352 {
9353 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9354 // Scan for the first non-phi operand.
9355 while (InValNo != NumOperandVals &&
9356 isa<PHINode>(PN.getIncomingValue(InValNo)))
9357 ++InValNo;
9358
9359 if (InValNo != NumOperandVals) {
9360 Value *NonPhiInVal = PN.getOperand(InValNo);
9361
9362 // Scan the rest of the operands to see if there are any conflicts, if so
9363 // there is no need to recursively scan other phis.
9364 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9365 Value *OpVal = PN.getIncomingValue(InValNo);
9366 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9367 break;
9368 }
9369
9370 // If we scanned over all operands, then we have one unique value plus
9371 // phi values. Scan PHI nodes to see if they all merge in each other or
9372 // the value.
9373 if (InValNo == NumOperandVals) {
9374 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9375 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9376 return ReplaceInstUsesWith(PN, NonPhiInVal);
9377 }
9378 }
9379 }
Chris Lattner60921c92003-12-19 05:58:40 +00009380 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009381}
9382
Reid Spencer17212df2006-12-12 09:18:51 +00009383static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9384 Instruction *InsertPoint,
9385 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009386 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9387 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009388 // We must cast correctly to the pointer type. Ensure that we
9389 // sign extend the integer value if it is smaller as this is
9390 // used for address computation.
9391 Instruction::CastOps opcode =
9392 (VTySize < PtrSize ? Instruction::SExt :
9393 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9394 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009395}
9396
Chris Lattnera1be5662002-05-02 17:06:02 +00009397
Chris Lattner7e708292002-06-25 16:13:24 +00009398Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009399 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009400 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009401 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009402 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009403 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009404
Chris Lattnere87597f2004-10-16 18:11:37 +00009405 if (isa<UndefValue>(GEP.getOperand(0)))
9406 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9407
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009408 bool HasZeroPointerIndex = false;
9409 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9410 HasZeroPointerIndex = C->isNullValue();
9411
9412 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009413 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009414
Chris Lattner28977af2004-04-05 01:30:19 +00009415 // Eliminate unneeded casts for indices.
9416 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009417
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009418 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009419 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009420 if (isa<SequentialType>(*GTI)) {
9421 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009422 if (CI->getOpcode() == Instruction::ZExt ||
9423 CI->getOpcode() == Instruction::SExt) {
9424 const Type *SrcTy = CI->getOperand(0)->getType();
9425 // We can eliminate a cast from i32 to i64 iff the target
9426 // is a 32-bit pointer target.
9427 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9428 MadeChange = true;
9429 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009430 }
9431 }
9432 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009433 // If we are using a wider index than needed for this platform, shrink it
9434 // to what we need. If the incoming value needs a cast instruction,
9435 // insert it. This explicit cast can make subsequent optimizations more
9436 // obvious.
9437 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009438 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009439 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009440 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009441 MadeChange = true;
9442 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009443 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9444 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009445 GEP.setOperand(i, Op);
9446 MadeChange = true;
9447 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009448 }
Chris Lattner28977af2004-04-05 01:30:19 +00009449 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009450 }
Chris Lattner28977af2004-04-05 01:30:19 +00009451 if (MadeChange) return &GEP;
9452
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009453 // If this GEP instruction doesn't move the pointer, and if the input operand
9454 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9455 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009456 if (GEP.hasAllZeroIndices()) {
9457 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9458 // If the bitcast is of an allocation, and the allocation will be
9459 // converted to match the type of the cast, don't touch this.
9460 if (isa<AllocationInst>(BCI->getOperand(0))) {
9461 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009462 if (Instruction *I = visitBitCast(*BCI)) {
9463 if (I != BCI) {
9464 I->takeName(BCI);
9465 BCI->getParent()->getInstList().insert(BCI, I);
9466 ReplaceInstUsesWith(*BCI, I);
9467 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009468 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009469 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009470 }
9471 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9472 }
9473 }
9474
Chris Lattner90ac28c2002-08-02 19:29:35 +00009475 // Combine Indices - If the source pointer to this getelementptr instruction
9476 // is a getelementptr instruction, combine the indices of the two
9477 // getelementptr instructions into a single instruction.
9478 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009479 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009480 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009481 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009482
9483 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009484 // Note that if our source is a gep chain itself that we wait for that
9485 // chain to be resolved before we perform this transformation. This
9486 // avoids us creating a TON of code in some cases.
9487 //
9488 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9489 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9490 return 0; // Wait until our source is folded to completion.
9491
Chris Lattner72588fc2007-02-15 22:48:32 +00009492 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009493
9494 // Find out whether the last index in the source GEP is a sequential idx.
9495 bool EndsWithSequential = false;
9496 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9497 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009498 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009499
Chris Lattner90ac28c2002-08-02 19:29:35 +00009500 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009501 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009502 // Replace: gep (gep %P, long B), long A, ...
9503 // With: T = long A+B; gep %P, T, ...
9504 //
Chris Lattner620ce142004-05-07 22:09:22 +00009505 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009506 if (SO1 == Constant::getNullValue(SO1->getType())) {
9507 Sum = GO1;
9508 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9509 Sum = SO1;
9510 } else {
9511 // If they aren't the same type, convert both to an integer of the
9512 // target's pointer size.
9513 if (SO1->getType() != GO1->getType()) {
9514 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009515 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009516 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009517 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009518 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009519 unsigned PS = TD->getPointerSizeInBits();
9520 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009521 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009522 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009523
Duncan Sands514ab342007-11-01 20:53:16 +00009524 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009525 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009526 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009527 } else {
9528 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009529 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9530 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009531 }
9532 }
9533 }
Chris Lattner620ce142004-05-07 22:09:22 +00009534 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9535 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9536 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009537 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9538 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009539 }
Chris Lattner28977af2004-04-05 01:30:19 +00009540 }
Chris Lattner620ce142004-05-07 22:09:22 +00009541
9542 // Recycle the GEP we already have if possible.
9543 if (SrcGEPOperands.size() == 2) {
9544 GEP.setOperand(0, SrcGEPOperands[0]);
9545 GEP.setOperand(1, Sum);
9546 return &GEP;
9547 } else {
9548 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9549 SrcGEPOperands.end()-1);
9550 Indices.push_back(Sum);
9551 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9552 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009553 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009554 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009555 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009556 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009557 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9558 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009559 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9560 }
9561
9562 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009563 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9564 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009565
Chris Lattner620ce142004-05-07 22:09:22 +00009566 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009567 // GEP of global variable. If all of the indices for this GEP are
9568 // constants, we can promote this to a constexpr instead of an instruction.
9569
9570 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009571 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009572 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9573 for (; I != E && isa<Constant>(*I); ++I)
9574 Indices.push_back(cast<Constant>(*I));
9575
9576 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009577 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9578 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009579
9580 // Replace all uses of the GEP with the new constexpr...
9581 return ReplaceInstUsesWith(GEP, CE);
9582 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009583 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009584 if (!isa<PointerType>(X->getType())) {
9585 // Not interesting. Source pointer must be a cast from pointer.
9586 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009587 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9588 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009589 //
9590 // This occurs when the program declares an array extern like "int X[];"
9591 //
9592 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9593 const PointerType *XTy = cast<PointerType>(X->getType());
9594 if (const ArrayType *XATy =
9595 dyn_cast<ArrayType>(XTy->getElementType()))
9596 if (const ArrayType *CATy =
9597 dyn_cast<ArrayType>(CPTy->getElementType()))
9598 if (CATy->getElementType() == XATy->getElementType()) {
9599 // At this point, we know that the cast source type is a pointer
9600 // to an array of the same type as the destination pointer
9601 // array. Because the array type is never stepped over (there
9602 // is a leading zero) we can fold the cast into this GEP.
9603 GEP.setOperand(0, X);
9604 return &GEP;
9605 }
9606 } else if (GEP.getNumOperands() == 2) {
9607 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009608 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9609 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009610 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9611 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9612 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009613 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9614 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009615 Value *Idx[2];
9616 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9617 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009618 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009619 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009620 // V and GEP are both pointer types --> BitCast
9621 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009622 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009623
9624 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009625 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009626 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009627 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009628
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009629 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009630 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009631 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009632
9633 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9634 // allow either a mul, shift, or constant here.
9635 Value *NewIdx = 0;
9636 ConstantInt *Scale = 0;
9637 if (ArrayEltSize == 1) {
9638 NewIdx = GEP.getOperand(1);
9639 Scale = ConstantInt::get(NewIdx->getType(), 1);
9640 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009641 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009642 Scale = CI;
9643 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9644 if (Inst->getOpcode() == Instruction::Shl &&
9645 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009646 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9647 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9648 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009649 NewIdx = Inst->getOperand(0);
9650 } else if (Inst->getOpcode() == Instruction::Mul &&
9651 isa<ConstantInt>(Inst->getOperand(1))) {
9652 Scale = cast<ConstantInt>(Inst->getOperand(1));
9653 NewIdx = Inst->getOperand(0);
9654 }
9655 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009656
Chris Lattner7835cdd2005-09-13 18:36:04 +00009657 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009658 // out, perform the transformation. Note, we don't know whether Scale is
9659 // signed or not. We'll use unsigned version of division/modulo
9660 // operation after making sure Scale doesn't have the sign bit set.
9661 if (Scale && Scale->getSExtValue() >= 0LL &&
9662 Scale->getZExtValue() % ArrayEltSize == 0) {
9663 Scale = ConstantInt::get(Scale->getType(),
9664 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009665 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009666 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009667 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009668 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9669 NewIdx = InsertNewInstBefore(Sc, GEP);
9670 }
9671
9672 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009673 Value *Idx[2];
9674 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9675 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009676 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009677 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009678 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9679 // The NewGEP must be pointer typed, so must the old one -> BitCast
9680 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009681 }
9682 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009683 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009684 }
9685
Chris Lattner8a2a3112001-12-14 16:52:21 +00009686 return 0;
9687}
9688
Chris Lattner0864acf2002-11-04 16:18:53 +00009689Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9690 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009691 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009692 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9693 const Type *NewTy =
9694 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009695 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009696
9697 // Create and insert the replacement instruction...
9698 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009699 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009700 else {
9701 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009702 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009703 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009704
9705 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009706
Chris Lattner0864acf2002-11-04 16:18:53 +00009707 // Scan to the end of the allocation instructions, to skip over a block of
9708 // allocas if possible...
9709 //
9710 BasicBlock::iterator It = New;
9711 while (isa<AllocationInst>(*It)) ++It;
9712
9713 // Now that I is pointing to the first non-allocation-inst in the block,
9714 // insert our getelementptr instruction...
9715 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009716 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009717 Value *Idx[2];
9718 Idx[0] = NullIdx;
9719 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +00009720 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9721 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009722
9723 // Now make everything use the getelementptr instead of the original
9724 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009725 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009726 } else if (isa<UndefValue>(AI.getArraySize())) {
9727 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009728 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009729 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009730
9731 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9732 // Note that we only do this for alloca's, because malloc should allocate and
9733 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009734 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009735 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009736 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9737
Chris Lattner0864acf2002-11-04 16:18:53 +00009738 return 0;
9739}
9740
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009741Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9742 Value *Op = FI.getOperand(0);
9743
Chris Lattner17be6352004-10-18 02:59:09 +00009744 // free undef -> unreachable.
9745 if (isa<UndefValue>(Op)) {
9746 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009747 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009748 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009749 return EraseInstFromFunction(FI);
9750 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009751
Chris Lattner6160e852004-02-28 04:57:37 +00009752 // If we have 'free null' delete the instruction. This can happen in stl code
9753 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009754 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009755 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009756
9757 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9758 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9759 FI.setOperand(0, CI->getOperand(0));
9760 return &FI;
9761 }
9762
9763 // Change free (gep X, 0,0,0,0) into free(X)
9764 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9765 if (GEPI->hasAllZeroIndices()) {
9766 AddToWorkList(GEPI);
9767 FI.setOperand(0, GEPI->getOperand(0));
9768 return &FI;
9769 }
9770 }
9771
9772 // Change free(malloc) into nothing, if the malloc has a single use.
9773 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9774 if (MI->hasOneUse()) {
9775 EraseInstFromFunction(FI);
9776 return EraseInstFromFunction(*MI);
9777 }
Chris Lattner6160e852004-02-28 04:57:37 +00009778
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009779 return 0;
9780}
9781
9782
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009783/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009784static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009785 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009786 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009787 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009788
Devang Patel99db6ad2007-10-18 19:52:32 +00009789 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9790 // Instead of loading constant c string, use corresponding integer value
9791 // directly if string length is small enough.
9792 const std::string &Str = CE->getOperand(0)->getStringValue();
9793 if (!Str.empty()) {
9794 unsigned len = Str.length();
9795 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9796 unsigned numBits = Ty->getPrimitiveSizeInBits();
9797 // Replace LI with immediate integer store.
9798 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009799 APInt StrVal(numBits, 0);
9800 APInt SingleChar(numBits, 0);
9801 if (TD->isLittleEndian()) {
9802 for (signed i = len-1; i >= 0; i--) {
9803 SingleChar = (uint64_t) Str[i];
9804 StrVal = (StrVal << 8) | SingleChar;
9805 }
9806 } else {
9807 for (unsigned i = 0; i < len; i++) {
9808 SingleChar = (uint64_t) Str[i];
9809 StrVal = (StrVal << 8) | SingleChar;
9810 }
9811 // Append NULL at the end.
9812 SingleChar = 0;
9813 StrVal = (StrVal << 8) | SingleChar;
9814 }
9815 Value *NL = ConstantInt::get(StrVal);
9816 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009817 }
9818 }
9819 }
9820
Chris Lattnerb89e0712004-07-13 01:49:43 +00009821 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009822 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009823 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009824
Reid Spencer42230162007-01-22 05:51:25 +00009825 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009826 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009827 // If the source is an array, the code below will not succeed. Check to
9828 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9829 // constants.
9830 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9831 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9832 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009833 Value *Idxs[2];
9834 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9835 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009836 SrcTy = cast<PointerType>(CastOp->getType());
9837 SrcPTy = SrcTy->getElementType();
9838 }
9839
Reid Spencer42230162007-01-22 05:51:25 +00009840 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009841 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009842 // Do not allow turning this into a load of an integer, which is then
9843 // casted to a pointer, this pessimizes pointer analysis a lot.
9844 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009845 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9846 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009847
Chris Lattnerf9527852005-01-31 04:50:46 +00009848 // Okay, we are casting from one integer or pointer type to another of
9849 // the same size. Instead of casting the pointer before the load, cast
9850 // the result of the loaded value.
9851 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9852 CI->getName(),
9853 LI.isVolatile()),LI);
9854 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009855 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009856 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009857 }
9858 }
9859 return 0;
9860}
9861
Chris Lattnerc10aced2004-09-19 18:43:46 +00009862/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009863/// from this value cannot trap. If it is not obviously safe to load from the
9864/// specified pointer, we do a quick local scan of the basic block containing
9865/// ScanFrom, to determine if the address is already accessed.
9866static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009867 // If it is an alloca it is always safe to load from.
9868 if (isa<AllocaInst>(V)) return true;
9869
Duncan Sands46318cd2007-09-19 10:25:38 +00009870 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009871 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009872 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009873 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009874
9875 // Otherwise, be a little bit agressive by scanning the local block where we
9876 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009877 // from/to. If so, the previous load or store would have already trapped,
9878 // so there is no harm doing an extra load (also, CSE will later eliminate
9879 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009880 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9881
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009882 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009883 --BBI;
9884
9885 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9886 if (LI->getOperand(0) == V) return true;
9887 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9888 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009889
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009890 }
Chris Lattner8a375202004-09-19 19:18:10 +00009891 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009892}
9893
Chris Lattner8d2e8882007-08-11 18:48:48 +00009894/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9895/// until we find the underlying object a pointer is referring to or something
9896/// we don't understand. Note that the returned pointer may be offset from the
9897/// input, because we ignore GEP indices.
9898static Value *GetUnderlyingObject(Value *Ptr) {
9899 while (1) {
9900 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9901 if (CE->getOpcode() == Instruction::BitCast ||
9902 CE->getOpcode() == Instruction::GetElementPtr)
9903 Ptr = CE->getOperand(0);
9904 else
9905 return Ptr;
9906 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9907 Ptr = BCI->getOperand(0);
9908 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9909 Ptr = GEP->getOperand(0);
9910 } else {
9911 return Ptr;
9912 }
9913 }
9914}
9915
Chris Lattner833b8a42003-06-26 05:06:25 +00009916Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9917 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009918
Dan Gohman9941f742007-07-20 16:34:21 +00009919 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009920 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
9921 if (KnownAlign >
9922 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
9923 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +00009924 LI.setAlignment(KnownAlign);
9925
Chris Lattner37366c12005-05-01 04:24:53 +00009926 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009927 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009928 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009929 return Res;
9930
9931 // None of the following transforms are legal for volatile loads.
9932 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009933
Chris Lattner62f254d2005-09-12 22:00:15 +00009934 if (&LI.getParent()->front() != &LI) {
9935 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009936 // If the instruction immediately before this is a store to the same
9937 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009938 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9939 if (SI->getOperand(1) == LI.getOperand(0))
9940 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009941 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9942 if (LIB->getOperand(0) == LI.getOperand(0))
9943 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009944 }
Chris Lattner37366c12005-05-01 04:24:53 +00009945
Christopher Lambb15147e2007-12-29 07:56:53 +00009946 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9947 const Value *GEPI0 = GEPI->getOperand(0);
9948 // TODO: Consider a target hook for valid address spaces for this xform.
9949 if (isa<ConstantPointerNull>(GEPI0) &&
9950 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009951 // Insert a new store to null instruction before the load to indicate
9952 // that this code is not reachable. We do this instead of inserting
9953 // an unreachable instruction directly because we cannot modify the
9954 // CFG.
9955 new StoreInst(UndefValue::get(LI.getType()),
9956 Constant::getNullValue(Op->getType()), &LI);
9957 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9958 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009959 }
Chris Lattner37366c12005-05-01 04:24:53 +00009960
Chris Lattnere87597f2004-10-16 18:11:37 +00009961 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009962 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009963 // TODO: Consider a target hook for valid address spaces for this xform.
9964 if (isa<UndefValue>(C) || (C->isNullValue() &&
9965 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009966 // Insert a new store to null instruction before the load to indicate that
9967 // this code is not reachable. We do this instead of inserting an
9968 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009969 new StoreInst(UndefValue::get(LI.getType()),
9970 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009971 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009972 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009973
Chris Lattnere87597f2004-10-16 18:11:37 +00009974 // Instcombine load (constant global) into the value loaded.
9975 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009976 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009977 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009978
Chris Lattnere87597f2004-10-16 18:11:37 +00009979 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009980 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00009981 if (CE->getOpcode() == Instruction::GetElementPtr) {
9982 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009983 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009984 if (Constant *V =
9985 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009986 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009987 if (CE->getOperand(0)->isNullValue()) {
9988 // Insert a new store to null instruction before the load to indicate
9989 // that this code is not reachable. We do this instead of inserting
9990 // an unreachable instruction directly because we cannot modify the
9991 // CFG.
9992 new StoreInst(UndefValue::get(LI.getType()),
9993 Constant::getNullValue(Op->getType()), &LI);
9994 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9995 }
9996
Reid Spencer3da59db2006-11-27 01:05:10 +00009997 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009998 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009999 return Res;
10000 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010001 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010002 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010003
10004 // If this load comes from anywhere in a constant global, and if the global
10005 // is all undef or zero, we know what it loads.
10006 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10007 if (GV->isConstant() && GV->hasInitializer()) {
10008 if (GV->getInitializer()->isNullValue())
10009 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10010 else if (isa<UndefValue>(GV->getInitializer()))
10011 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10012 }
10013 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010014
Chris Lattner37366c12005-05-01 04:24:53 +000010015 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010016 // Change select and PHI nodes to select values instead of addresses: this
10017 // helps alias analysis out a lot, allows many others simplifications, and
10018 // exposes redundancy in the code.
10019 //
10020 // Note that we cannot do the transformation unless we know that the
10021 // introduced loads cannot trap! Something like this is valid as long as
10022 // the condition is always false: load (select bool %C, int* null, int* %G),
10023 // but it would not be valid if we transformed it to load from null
10024 // unconditionally.
10025 //
10026 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10027 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010028 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10029 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010030 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010031 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010032 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010033 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010034 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010035 }
10036
Chris Lattner684fe212004-09-23 15:46:00 +000010037 // load (select (cond, null, P)) -> load P
10038 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10039 if (C->isNullValue()) {
10040 LI.setOperand(0, SI->getOperand(2));
10041 return &LI;
10042 }
10043
10044 // load (select (cond, P, null)) -> load P
10045 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10046 if (C->isNullValue()) {
10047 LI.setOperand(0, SI->getOperand(1));
10048 return &LI;
10049 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010050 }
10051 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010052 return 0;
10053}
10054
Reid Spencer55af2b52007-01-19 21:20:31 +000010055/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010056/// when possible.
10057static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10058 User *CI = cast<User>(SI.getOperand(1));
10059 Value *CastOp = CI->getOperand(0);
10060
10061 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10062 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10063 const Type *SrcPTy = SrcTy->getElementType();
10064
Reid Spencer42230162007-01-22 05:51:25 +000010065 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010066 // If the source is an array, the code below will not succeed. Check to
10067 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10068 // constants.
10069 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10070 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10071 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010072 Value* Idxs[2];
10073 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10074 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010075 SrcTy = cast<PointerType>(CastOp->getType());
10076 SrcPTy = SrcTy->getElementType();
10077 }
10078
Reid Spencer67f827c2007-01-20 23:35:48 +000010079 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10080 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10081 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010082
10083 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010084 // the same size. Instead of casting the pointer before
10085 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010086 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010087 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010088 Instruction::CastOps opcode = Instruction::BitCast;
10089 const Type* CastSrcTy = SIOp0->getType();
10090 const Type* CastDstTy = SrcPTy;
10091 if (isa<PointerType>(CastDstTy)) {
10092 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010093 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010094 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010095 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010096 opcode = Instruction::PtrToInt;
10097 }
10098 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010099 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010100 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010101 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +000010102 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
10103 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010104 return new StoreInst(NewCast, CastOp);
10105 }
10106 }
10107 }
10108 return 0;
10109}
10110
Chris Lattner2f503e62005-01-31 05:36:43 +000010111Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10112 Value *Val = SI.getOperand(0);
10113 Value *Ptr = SI.getOperand(1);
10114
10115 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010116 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010117 ++NumCombined;
10118 return 0;
10119 }
Chris Lattner836692d2007-01-15 06:51:56 +000010120
10121 // If the RHS is an alloca with a single use, zapify the store, making the
10122 // alloca dead.
10123 if (Ptr->hasOneUse()) {
10124 if (isa<AllocaInst>(Ptr)) {
10125 EraseInstFromFunction(SI);
10126 ++NumCombined;
10127 return 0;
10128 }
10129
10130 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10131 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10132 GEP->getOperand(0)->hasOneUse()) {
10133 EraseInstFromFunction(SI);
10134 ++NumCombined;
10135 return 0;
10136 }
10137 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010138
Dan Gohman9941f742007-07-20 16:34:21 +000010139 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010140 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10141 if (KnownAlign >
10142 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10143 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010144 SI.setAlignment(KnownAlign);
10145
Chris Lattner9ca96412006-02-08 03:25:32 +000010146 // Do really simple DSE, to catch cases where there are several consequtive
10147 // stores to the same location, separated by a few arithmetic operations. This
10148 // situation often occurs with bitfield accesses.
10149 BasicBlock::iterator BBI = &SI;
10150 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10151 --ScanInsts) {
10152 --BBI;
10153
10154 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10155 // Prev store isn't volatile, and stores to the same location?
10156 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10157 ++NumDeadStore;
10158 ++BBI;
10159 EraseInstFromFunction(*PrevSI);
10160 continue;
10161 }
10162 break;
10163 }
10164
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010165 // If this is a load, we have to stop. However, if the loaded value is from
10166 // the pointer we're loading and is producing the pointer we're storing,
10167 // then *this* store is dead (X = load P; store X -> P).
10168 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010169 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010170 EraseInstFromFunction(SI);
10171 ++NumCombined;
10172 return 0;
10173 }
10174 // Otherwise, this is a load from some other location. Stores before it
10175 // may not be dead.
10176 break;
10177 }
10178
Chris Lattner9ca96412006-02-08 03:25:32 +000010179 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010180 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010181 break;
10182 }
10183
10184
10185 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010186
10187 // store X, null -> turns into 'unreachable' in SimplifyCFG
10188 if (isa<ConstantPointerNull>(Ptr)) {
10189 if (!isa<UndefValue>(Val)) {
10190 SI.setOperand(0, UndefValue::get(Val->getType()));
10191 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010192 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010193 ++NumCombined;
10194 }
10195 return 0; // Do not modify these!
10196 }
10197
10198 // store undef, Ptr -> noop
10199 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010200 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010201 ++NumCombined;
10202 return 0;
10203 }
10204
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010205 // If the pointer destination is a cast, see if we can fold the cast into the
10206 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010207 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010208 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10209 return Res;
10210 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010211 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010212 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10213 return Res;
10214
Chris Lattner408902b2005-09-12 23:23:25 +000010215
10216 // If this store is the last instruction in the basic block, and if the block
10217 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010218 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010219 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010220 if (BI->isUnconditional())
10221 if (SimplifyStoreAtEndOfBlock(SI))
10222 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010223
Chris Lattner2f503e62005-01-31 05:36:43 +000010224 return 0;
10225}
10226
Chris Lattner3284d1f2007-04-15 00:07:55 +000010227/// SimplifyStoreAtEndOfBlock - Turn things like:
10228/// if () { *P = v1; } else { *P = v2 }
10229/// into a phi node with a store in the successor.
10230///
Chris Lattner31755a02007-04-15 01:02:18 +000010231/// Simplify things like:
10232/// *P = v1; if () { *P = v2; }
10233/// into a phi node with a store in the successor.
10234///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010235bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10236 BasicBlock *StoreBB = SI.getParent();
10237
10238 // Check to see if the successor block has exactly two incoming edges. If
10239 // so, see if the other predecessor contains a store to the same location.
10240 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010241 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010242
10243 // Determine whether Dest has exactly two predecessors and, if so, compute
10244 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010245 pred_iterator PI = pred_begin(DestBB);
10246 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010247 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010248 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010249 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010250 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010251 return false;
10252
10253 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010254 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010255 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010256 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010257 }
Chris Lattner31755a02007-04-15 01:02:18 +000010258 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010259 return false;
10260
10261
Chris Lattner31755a02007-04-15 01:02:18 +000010262 // Verify that the other block ends in a branch and is not otherwise empty.
10263 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010264 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010265 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010266 return false;
10267
Chris Lattner31755a02007-04-15 01:02:18 +000010268 // If the other block ends in an unconditional branch, check for the 'if then
10269 // else' case. there is an instruction before the branch.
10270 StoreInst *OtherStore = 0;
10271 if (OtherBr->isUnconditional()) {
10272 // If this isn't a store, or isn't a store to the same location, bail out.
10273 --BBI;
10274 OtherStore = dyn_cast<StoreInst>(BBI);
10275 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10276 return false;
10277 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010278 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010279 // destinations is StoreBB, then we have the if/then case.
10280 if (OtherBr->getSuccessor(0) != StoreBB &&
10281 OtherBr->getSuccessor(1) != StoreBB)
10282 return false;
10283
10284 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010285 // if/then triangle. See if there is a store to the same ptr as SI that
10286 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010287 for (;; --BBI) {
10288 // Check to see if we find the matching store.
10289 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10290 if (OtherStore->getOperand(1) != SI.getOperand(1))
10291 return false;
10292 break;
10293 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010294 // If we find something that may be using the stored value, or if we run
10295 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010296 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10297 BBI == OtherBB->begin())
10298 return false;
10299 }
10300
10301 // In order to eliminate the store in OtherBr, we have to
10302 // make sure nothing reads the stored value in StoreBB.
10303 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10304 // FIXME: This should really be AA driven.
10305 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10306 return false;
10307 }
10308 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010309
Chris Lattner31755a02007-04-15 01:02:18 +000010310 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010311 Value *MergedVal = OtherStore->getOperand(0);
10312 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010313 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010314 PN->reserveOperandSpace(2);
10315 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010316 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10317 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010318 }
10319
10320 // Advance to a place where it is safe to insert the new store and
10321 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010322 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010323 while (isa<PHINode>(BBI)) ++BBI;
10324 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10325 OtherStore->isVolatile()), *BBI);
10326
10327 // Nuke the old stores.
10328 EraseInstFromFunction(SI);
10329 EraseInstFromFunction(*OtherStore);
10330 ++NumCombined;
10331 return true;
10332}
10333
Chris Lattner2f503e62005-01-31 05:36:43 +000010334
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010335Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10336 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010337 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010338 BasicBlock *TrueDest;
10339 BasicBlock *FalseDest;
10340 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10341 !isa<Constant>(X)) {
10342 // Swap Destinations and condition...
10343 BI.setCondition(X);
10344 BI.setSuccessor(0, FalseDest);
10345 BI.setSuccessor(1, TrueDest);
10346 return &BI;
10347 }
10348
Reid Spencere4d87aa2006-12-23 06:05:41 +000010349 // Cannonicalize fcmp_one -> fcmp_oeq
10350 FCmpInst::Predicate FPred; Value *Y;
10351 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10352 TrueDest, FalseDest)))
10353 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10354 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10355 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010356 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010357 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10358 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010359 // Swap Destinations and condition...
10360 BI.setCondition(NewSCC);
10361 BI.setSuccessor(0, FalseDest);
10362 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010363 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010364 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010365 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010366 return &BI;
10367 }
10368
10369 // Cannonicalize icmp_ne -> icmp_eq
10370 ICmpInst::Predicate IPred;
10371 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10372 TrueDest, FalseDest)))
10373 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10374 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10375 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10376 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010377 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010378 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10379 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010380 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010381 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010382 BI.setSuccessor(0, FalseDest);
10383 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010384 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010385 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010386 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010387 return &BI;
10388 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010389
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010390 return 0;
10391}
Chris Lattner0864acf2002-11-04 16:18:53 +000010392
Chris Lattner46238a62004-07-03 00:26:11 +000010393Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10394 Value *Cond = SI.getCondition();
10395 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10396 if (I->getOpcode() == Instruction::Add)
10397 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10398 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10399 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010400 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010401 AddRHS));
10402 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010403 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010404 return &SI;
10405 }
10406 }
10407 return 0;
10408}
10409
Chris Lattner220b0cf2006-03-05 00:22:33 +000010410/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10411/// is to leave as a vector operation.
10412static bool CheapToScalarize(Value *V, bool isConstant) {
10413 if (isa<ConstantAggregateZero>(V))
10414 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010415 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010416 if (isConstant) return true;
10417 // If all elts are the same, we can extract.
10418 Constant *Op0 = C->getOperand(0);
10419 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10420 if (C->getOperand(i) != Op0)
10421 return false;
10422 return true;
10423 }
10424 Instruction *I = dyn_cast<Instruction>(V);
10425 if (!I) return false;
10426
10427 // Insert element gets simplified to the inserted element or is deleted if
10428 // this is constant idx extract element and its a constant idx insertelt.
10429 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10430 isa<ConstantInt>(I->getOperand(2)))
10431 return true;
10432 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10433 return true;
10434 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10435 if (BO->hasOneUse() &&
10436 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10437 CheapToScalarize(BO->getOperand(1), isConstant)))
10438 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010439 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10440 if (CI->hasOneUse() &&
10441 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10442 CheapToScalarize(CI->getOperand(1), isConstant)))
10443 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010444
10445 return false;
10446}
10447
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010448/// Read and decode a shufflevector mask.
10449///
10450/// It turns undef elements into values that are larger than the number of
10451/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010452static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10453 unsigned NElts = SVI->getType()->getNumElements();
10454 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10455 return std::vector<unsigned>(NElts, 0);
10456 if (isa<UndefValue>(SVI->getOperand(2)))
10457 return std::vector<unsigned>(NElts, 2*NElts);
10458
10459 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010460 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010461 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10462 if (isa<UndefValue>(CP->getOperand(i)))
10463 Result.push_back(NElts*2); // undef -> 8
10464 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010465 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010466 return Result;
10467}
10468
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010469/// FindScalarElement - Given a vector and an element number, see if the scalar
10470/// value is already around as a register, for example if it were inserted then
10471/// extracted from the vector.
10472static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010473 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10474 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010475 unsigned Width = PTy->getNumElements();
10476 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010477 return UndefValue::get(PTy->getElementType());
10478
10479 if (isa<UndefValue>(V))
10480 return UndefValue::get(PTy->getElementType());
10481 else if (isa<ConstantAggregateZero>(V))
10482 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010483 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010484 return CP->getOperand(EltNo);
10485 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10486 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010487 if (!isa<ConstantInt>(III->getOperand(2)))
10488 return 0;
10489 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010490
10491 // If this is an insert to the element we are looking for, return the
10492 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010493 if (EltNo == IIElt)
10494 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010495
10496 // Otherwise, the insertelement doesn't modify the value, recurse on its
10497 // vector input.
10498 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010499 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010500 unsigned InEl = getShuffleMask(SVI)[EltNo];
10501 if (InEl < Width)
10502 return FindScalarElement(SVI->getOperand(0), InEl);
10503 else if (InEl < Width*2)
10504 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10505 else
10506 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010507 }
10508
10509 // Otherwise, we don't know.
10510 return 0;
10511}
10512
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010513Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010514
Dan Gohman07a96762007-07-16 14:29:03 +000010515 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010516 if (isa<UndefValue>(EI.getOperand(0)))
10517 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10518
Dan Gohman07a96762007-07-16 14:29:03 +000010519 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010520 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10521 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10522
Reid Spencer9d6565a2007-02-15 02:26:10 +000010523 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010524 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010525 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010526 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010527 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010528 if (C->getOperand(i) != op0) {
10529 op0 = 0;
10530 break;
10531 }
10532 if (op0)
10533 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010534 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010535
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010536 // If extracting a specified index from the vector, see if we can recursively
10537 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010538 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010539 unsigned IndexVal = IdxC->getZExtValue();
10540 unsigned VectorWidth =
10541 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10542
10543 // If this is extracting an invalid index, turn this into undef, to avoid
10544 // crashing the code below.
10545 if (IndexVal >= VectorWidth)
10546 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10547
Chris Lattner867b99f2006-10-05 06:55:50 +000010548 // This instruction only demands the single element from the input vector.
10549 // If the input vector has a single use, simplify it based on this use
10550 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010551 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010552 uint64_t UndefElts;
10553 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010554 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010555 UndefElts)) {
10556 EI.setOperand(0, V);
10557 return &EI;
10558 }
10559 }
10560
Reid Spencerb83eb642006-10-20 07:07:24 +000010561 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010562 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010563
10564 // If the this extractelement is directly using a bitcast from a vector of
10565 // the same number of elements, see if we can find the source element from
10566 // it. In this case, we will end up needing to bitcast the scalars.
10567 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10568 if (const VectorType *VT =
10569 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10570 if (VT->getNumElements() == VectorWidth)
10571 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10572 return new BitCastInst(Elt, EI.getType());
10573 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010574 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010575
Chris Lattner73fa49d2006-05-25 22:53:38 +000010576 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010577 if (I->hasOneUse()) {
10578 // Push extractelement into predecessor operation if legal and
10579 // profitable to do so
10580 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010581 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10582 if (CheapToScalarize(BO, isConstantElt)) {
10583 ExtractElementInst *newEI0 =
10584 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10585 EI.getName()+".lhs");
10586 ExtractElementInst *newEI1 =
10587 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10588 EI.getName()+".rhs");
10589 InsertNewInstBefore(newEI0, EI);
10590 InsertNewInstBefore(newEI1, EI);
10591 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10592 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010593 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010594 unsigned AS =
10595 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010596 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10597 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010598 GetElementPtrInst *GEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010599 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010600 InsertNewInstBefore(GEP, EI);
10601 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010602 }
10603 }
10604 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10605 // Extracting the inserted element?
10606 if (IE->getOperand(2) == EI.getOperand(1))
10607 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10608 // If the inserted and extracted elements are constants, they must not
10609 // be the same value, extract from the pre-inserted value instead.
10610 if (isa<Constant>(IE->getOperand(2)) &&
10611 isa<Constant>(EI.getOperand(1))) {
10612 AddUsesToWorkList(EI);
10613 EI.setOperand(0, IE->getOperand(0));
10614 return &EI;
10615 }
10616 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10617 // If this is extracting an element from a shufflevector, figure out where
10618 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010619 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10620 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010621 Value *Src;
10622 if (SrcIdx < SVI->getType()->getNumElements())
10623 Src = SVI->getOperand(0);
10624 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10625 SrcIdx -= SVI->getType()->getNumElements();
10626 Src = SVI->getOperand(1);
10627 } else {
10628 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010629 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010630 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010631 }
10632 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010633 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010634 return 0;
10635}
10636
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010637/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10638/// elements from either LHS or RHS, return the shuffle mask and true.
10639/// Otherwise, return false.
10640static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10641 std::vector<Constant*> &Mask) {
10642 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10643 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010644 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010645
10646 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010647 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010648 return true;
10649 } else if (V == LHS) {
10650 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010651 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010652 return true;
10653 } else if (V == RHS) {
10654 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010655 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010656 return true;
10657 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10658 // If this is an insert of an extract from some other vector, include it.
10659 Value *VecOp = IEI->getOperand(0);
10660 Value *ScalarOp = IEI->getOperand(1);
10661 Value *IdxOp = IEI->getOperand(2);
10662
Chris Lattnerd929f062006-04-27 21:14:21 +000010663 if (!isa<ConstantInt>(IdxOp))
10664 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010665 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010666
10667 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10668 // Okay, we can handle this if the vector we are insertinting into is
10669 // transitively ok.
10670 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10671 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010672 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010673 return true;
10674 }
10675 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10676 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010677 EI->getOperand(0)->getType() == V->getType()) {
10678 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010679 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010680
10681 // This must be extracting from either LHS or RHS.
10682 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10683 // Okay, we can handle this if the vector we are insertinting into is
10684 // transitively ok.
10685 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10686 // If so, update the mask to reflect the inserted value.
10687 if (EI->getOperand(0) == LHS) {
10688 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010689 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010690 } else {
10691 assert(EI->getOperand(0) == RHS);
10692 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010693 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010694
10695 }
10696 return true;
10697 }
10698 }
10699 }
10700 }
10701 }
10702 // TODO: Handle shufflevector here!
10703
10704 return false;
10705}
10706
10707/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10708/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10709/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010710static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010711 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010712 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010713 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010714 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010715 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010716
10717 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010718 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010719 return V;
10720 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010721 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010722 return V;
10723 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10724 // If this is an insert of an extract from some other vector, include it.
10725 Value *VecOp = IEI->getOperand(0);
10726 Value *ScalarOp = IEI->getOperand(1);
10727 Value *IdxOp = IEI->getOperand(2);
10728
10729 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10730 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10731 EI->getOperand(0)->getType() == V->getType()) {
10732 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010733 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10734 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010735
10736 // Either the extracted from or inserted into vector must be RHSVec,
10737 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010738 if (EI->getOperand(0) == RHS || RHS == 0) {
10739 RHS = EI->getOperand(0);
10740 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010741 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010742 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010743 return V;
10744 }
10745
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010746 if (VecOp == RHS) {
10747 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010748 // Everything but the extracted element is replaced with the RHS.
10749 for (unsigned i = 0; i != NumElts; ++i) {
10750 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010751 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010752 }
10753 return V;
10754 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010755
10756 // If this insertelement is a chain that comes from exactly these two
10757 // vectors, return the vector and the effective shuffle.
10758 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10759 return EI->getOperand(0);
10760
Chris Lattnerefb47352006-04-15 01:39:45 +000010761 }
10762 }
10763 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010764 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010765
10766 // Otherwise, can't do anything fancy. Return an identity vector.
10767 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010768 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010769 return V;
10770}
10771
10772Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10773 Value *VecOp = IE.getOperand(0);
10774 Value *ScalarOp = IE.getOperand(1);
10775 Value *IdxOp = IE.getOperand(2);
10776
Chris Lattner599ded12007-04-09 01:11:16 +000010777 // Inserting an undef or into an undefined place, remove this.
10778 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10779 ReplaceInstUsesWith(IE, VecOp);
10780
Chris Lattnerefb47352006-04-15 01:39:45 +000010781 // If the inserted element was extracted from some other vector, and if the
10782 // indexes are constant, try to turn this into a shufflevector operation.
10783 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10784 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10785 EI->getOperand(0)->getType() == IE.getType()) {
10786 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010787 unsigned ExtractedIdx =
10788 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010789 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010790
10791 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10792 return ReplaceInstUsesWith(IE, VecOp);
10793
10794 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10795 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10796
10797 // If we are extracting a value from a vector, then inserting it right
10798 // back into the same place, just use the input vector.
10799 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10800 return ReplaceInstUsesWith(IE, VecOp);
10801
10802 // We could theoretically do this for ANY input. However, doing so could
10803 // turn chains of insertelement instructions into a chain of shufflevector
10804 // instructions, and right now we do not merge shufflevectors. As such,
10805 // only do this in a situation where it is clear that there is benefit.
10806 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10807 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10808 // the values of VecOp, except then one read from EIOp0.
10809 // Build a new shuffle mask.
10810 std::vector<Constant*> Mask;
10811 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010812 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010813 else {
10814 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010815 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010816 NumVectorElts));
10817 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010818 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010819 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010820 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010821 }
10822
10823 // If this insertelement isn't used by some other insertelement, turn it
10824 // (and any insertelements it points to), into one big shuffle.
10825 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10826 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010827 Value *RHS = 0;
10828 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10829 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10830 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010831 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010832 }
10833 }
10834 }
10835
10836 return 0;
10837}
10838
10839
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010840Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10841 Value *LHS = SVI.getOperand(0);
10842 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010843 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010844
10845 bool MadeChange = false;
10846
Chris Lattner867b99f2006-10-05 06:55:50 +000010847 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010848 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010849 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10850
Chris Lattnere4929dd2007-01-05 07:36:08 +000010851 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010852 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010853 if (isa<UndefValue>(SVI.getOperand(1))) {
10854 // Scan to see if there are any references to the RHS. If so, replace them
10855 // with undef element refs and set MadeChange to true.
10856 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10857 if (Mask[i] >= e && Mask[i] != 2*e) {
10858 Mask[i] = 2*e;
10859 MadeChange = true;
10860 }
10861 }
10862
10863 if (MadeChange) {
10864 // Remap any references to RHS to use LHS.
10865 std::vector<Constant*> Elts;
10866 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10867 if (Mask[i] == 2*e)
10868 Elts.push_back(UndefValue::get(Type::Int32Ty));
10869 else
10870 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10871 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010872 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010873 }
10874 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010875
Chris Lattner863bcff2006-05-25 23:48:38 +000010876 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10877 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10878 if (LHS == RHS || isa<UndefValue>(LHS)) {
10879 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010880 // shuffle(undef,undef,mask) -> undef.
10881 return ReplaceInstUsesWith(SVI, LHS);
10882 }
10883
Chris Lattner863bcff2006-05-25 23:48:38 +000010884 // Remap any references to RHS to use LHS.
10885 std::vector<Constant*> Elts;
10886 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010887 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010888 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010889 else {
10890 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10891 (Mask[i] < e && isa<UndefValue>(LHS)))
10892 Mask[i] = 2*e; // Turn into undef.
10893 else
10894 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010895 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010896 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010897 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010898 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010899 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010900 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010901 LHS = SVI.getOperand(0);
10902 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010903 MadeChange = true;
10904 }
10905
Chris Lattner7b2e27922006-05-26 00:29:06 +000010906 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010907 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010908
Chris Lattner863bcff2006-05-25 23:48:38 +000010909 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10910 if (Mask[i] >= e*2) continue; // Ignore undef values.
10911 // Is this an identity shuffle of the LHS value?
10912 isLHSID &= (Mask[i] == i);
10913
10914 // Is this an identity shuffle of the RHS value?
10915 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010916 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010917
Chris Lattner863bcff2006-05-25 23:48:38 +000010918 // Eliminate identity shuffles.
10919 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10920 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010921
Chris Lattner7b2e27922006-05-26 00:29:06 +000010922 // If the LHS is a shufflevector itself, see if we can combine it with this
10923 // one without producing an unusual shuffle. Here we are really conservative:
10924 // we are absolutely afraid of producing a shuffle mask not in the input
10925 // program, because the code gen may not be smart enough to turn a merged
10926 // shuffle into two specific shuffles: it may produce worse code. As such,
10927 // we only merge two shuffles if the result is one of the two input shuffle
10928 // masks. In this case, merging the shuffles just removes one instruction,
10929 // which we know is safe. This is good for things like turning:
10930 // (splat(splat)) -> splat.
10931 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10932 if (isa<UndefValue>(RHS)) {
10933 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10934
10935 std::vector<unsigned> NewMask;
10936 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10937 if (Mask[i] >= 2*e)
10938 NewMask.push_back(2*e);
10939 else
10940 NewMask.push_back(LHSMask[Mask[i]]);
10941
10942 // If the result mask is equal to the src shuffle or this shuffle mask, do
10943 // the replacement.
10944 if (NewMask == LHSMask || NewMask == Mask) {
10945 std::vector<Constant*> Elts;
10946 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10947 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010948 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010949 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010950 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010951 }
10952 }
10953 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10954 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010955 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010956 }
10957 }
10958 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010959
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010960 return MadeChange ? &SVI : 0;
10961}
10962
10963
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010964
Chris Lattnerea1c4542004-12-08 23:43:58 +000010965
10966/// TryToSinkInstruction - Try to move the specified instruction from its
10967/// current block into the beginning of DestBlock, which can only happen if it's
10968/// safe to move the instruction past all of the instructions between it and the
10969/// end of its block.
10970static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10971 assert(I->hasOneUse() && "Invariants didn't hold!");
10972
Chris Lattner108e9022005-10-27 17:13:11 +000010973 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10974 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010975
Chris Lattnerea1c4542004-12-08 23:43:58 +000010976 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010977 if (isa<AllocaInst>(I) && I->getParent() ==
10978 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010979 return false;
10980
Chris Lattner96a52a62004-12-09 07:14:34 +000010981 // We can only sink load instructions if there is nothing between the load and
10982 // the end of block that could change the value.
10983 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010984 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10985 Scan != E; ++Scan)
10986 if (Scan->mayWriteToMemory())
10987 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010988 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010989
10990 BasicBlock::iterator InsertPos = DestBlock->begin();
10991 while (isa<PHINode>(InsertPos)) ++InsertPos;
10992
Chris Lattner4bc5f802005-08-08 19:11:57 +000010993 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010994 ++NumSunkInst;
10995 return true;
10996}
10997
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010998
10999/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11000/// all reachable code to the worklist.
11001///
11002/// This has a couple of tricks to make the code faster and more powerful. In
11003/// particular, we constant fold and DCE instructions as we go, to avoid adding
11004/// them to the worklist (this significantly speeds up instcombine on code where
11005/// many instructions are dead or constant). Additionally, if we find a branch
11006/// whose condition is a known constant, we only visit the reachable successors.
11007///
11008static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011009 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011010 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011011 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011012 std::vector<BasicBlock*> Worklist;
11013 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011014
Chris Lattner2c7718a2007-03-23 19:17:18 +000011015 while (!Worklist.empty()) {
11016 BB = Worklist.back();
11017 Worklist.pop_back();
11018
11019 // We have now visited this block! If we've already been here, ignore it.
11020 if (!Visited.insert(BB)) continue;
11021
11022 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11023 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011024
Chris Lattner2c7718a2007-03-23 19:17:18 +000011025 // DCE instruction if trivially dead.
11026 if (isInstructionTriviallyDead(Inst)) {
11027 ++NumDeadInst;
11028 DOUT << "IC: DCE: " << *Inst;
11029 Inst->eraseFromParent();
11030 continue;
11031 }
11032
11033 // ConstantProp instruction if trivially constant.
11034 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11035 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11036 Inst->replaceAllUsesWith(C);
11037 ++NumConstProp;
11038 Inst->eraseFromParent();
11039 continue;
11040 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011041
Chris Lattner2c7718a2007-03-23 19:17:18 +000011042 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011043 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011044
11045 // Recursively visit successors. If this is a branch or switch on a
11046 // constant, only visit the reachable successor.
Nick Lewycky91436992008-03-09 08:50:23 +000011047 if (BB->getUnwindDest())
11048 Worklist.push_back(BB->getUnwindDest());
Chris Lattner2c7718a2007-03-23 19:17:18 +000011049 TerminatorInst *TI = BB->getTerminator();
11050 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11051 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11052 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011053 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11054 if (ReachableBB != BB->getUnwindDest())
11055 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011056 continue;
11057 }
11058 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11059 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11060 // See if this is an explicit destination.
11061 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11062 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011063 BasicBlock *ReachableBB = SI->getSuccessor(i);
11064 if (ReachableBB != BB->getUnwindDest())
11065 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011066 continue;
11067 }
11068
11069 // Otherwise it is the default destination.
11070 Worklist.push_back(SI->getSuccessor(0));
11071 continue;
11072 }
11073 }
11074
11075 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11076 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011077 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011078}
11079
Chris Lattnerec9c3582007-03-03 02:04:50 +000011080bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011081 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011082 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011083
11084 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11085 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011086
Chris Lattnerb3d59702005-07-07 20:40:38 +000011087 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011088 // Do a depth-first traversal of the function, populate the worklist with
11089 // the reachable instructions. Ignore blocks that are not reachable. Keep
11090 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011091 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011092 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011093
Chris Lattnerb3d59702005-07-07 20:40:38 +000011094 // Do a quick scan over the function. If we find any blocks that are
11095 // unreachable, remove any instructions inside of them. This prevents
11096 // the instcombine code from having to deal with some bad special cases.
11097 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11098 if (!Visited.count(BB)) {
11099 Instruction *Term = BB->getTerminator();
11100 while (Term != BB->begin()) { // Remove instrs bottom-up
11101 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011102
Bill Wendlingb7427032006-11-26 09:46:52 +000011103 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011104 ++NumDeadInst;
11105
11106 if (!I->use_empty())
11107 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11108 I->eraseFromParent();
11109 }
11110 }
11111 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011112
Chris Lattnerdbab3862007-03-02 21:28:56 +000011113 while (!Worklist.empty()) {
11114 Instruction *I = RemoveOneFromWorkList();
11115 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011116
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011117 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011118 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011119 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011120 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011121 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011122 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011123
Bill Wendlingb7427032006-11-26 09:46:52 +000011124 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011125
11126 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011127 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011128 continue;
11129 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011130
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011131 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011132 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011133 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011134
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011135 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011136 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011137 ReplaceInstUsesWith(*I, C);
11138
Chris Lattner62b14df2002-09-02 04:59:56 +000011139 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011140 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011141 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011142 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011143 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011144
Chris Lattnerea1c4542004-12-08 23:43:58 +000011145 // See if we can trivially sink this instruction to a successor basic block.
11146 if (I->hasOneUse()) {
11147 BasicBlock *BB = I->getParent();
11148 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11149 if (UserParent != BB) {
11150 bool UserIsSuccessor = false;
11151 // See if the user is one of our successors.
11152 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11153 if (*SI == UserParent) {
11154 UserIsSuccessor = true;
11155 break;
11156 }
11157
11158 // If the user is one of our immediate successors, and if that successor
11159 // only has us as a predecessors (we'd have to split the critical edge
11160 // otherwise), we can keep going.
11161 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11162 next(pred_begin(UserParent)) == pred_end(UserParent))
11163 // Okay, the CFG is simple enough, try to sink this instruction.
11164 Changed |= TryToSinkInstruction(I, UserParent);
11165 }
11166 }
11167
Chris Lattner8a2a3112001-12-14 16:52:21 +000011168 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011169#ifndef NDEBUG
11170 std::string OrigI;
11171#endif
11172 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011173 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011174 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011175 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011176 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011177 DOUT << "IC: Old = " << *I
11178 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011179
Chris Lattnerf523d062004-06-09 05:08:07 +000011180 // Everything uses the new instruction now.
11181 I->replaceAllUsesWith(Result);
11182
11183 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011184 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011185 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011186
Chris Lattner6934a042007-02-11 01:23:03 +000011187 // Move the name to the new instruction first.
11188 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011189
11190 // Insert the new instruction into the basic block...
11191 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011192 BasicBlock::iterator InsertPos = I;
11193
11194 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11195 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11196 ++InsertPos;
11197
11198 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011199
Chris Lattner00d51312004-05-01 23:27:23 +000011200 // Make sure that we reprocess all operands now that we reduced their
11201 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011202 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011203
Chris Lattnerf523d062004-06-09 05:08:07 +000011204 // Instructions can end up on the worklist more than once. Make sure
11205 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011206 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011207
11208 // Erase the old instruction.
11209 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011210 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011211#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011212 DOUT << "IC: Mod = " << OrigI
11213 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011214#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011215
Chris Lattner90ac28c2002-08-02 19:29:35 +000011216 // If the instruction was modified, it's possible that it is now dead.
11217 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011218 if (isInstructionTriviallyDead(I)) {
11219 // Make sure we process all operands now that we are reducing their
11220 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011221 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011222
Chris Lattner00d51312004-05-01 23:27:23 +000011223 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011224 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011225 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011226 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011227 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011228 AddToWorkList(I);
11229 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011230 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011231 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011232 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011233 }
11234 }
11235
Chris Lattnerec9c3582007-03-03 02:04:50 +000011236 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011237
11238 // Do an explicit clear, this shrinks the map if needed.
11239 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011240 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011241}
11242
Chris Lattnerec9c3582007-03-03 02:04:50 +000011243
11244bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011245 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11246
Chris Lattnerec9c3582007-03-03 02:04:50 +000011247 bool EverMadeChange = false;
11248
11249 // Iterate while there is work to do.
11250 unsigned Iteration = 0;
11251 while (DoOneIteration(F, Iteration++))
11252 EverMadeChange = true;
11253 return EverMadeChange;
11254}
11255
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011256FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011257 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011258}
Brian Gaeked0fde302003-11-11 22:41:34 +000011259