blob: 06620557daa6018dbca208a76577590ae8de9405 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000048#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000051#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000052#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000054#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000060#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000061#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000062using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000063using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000070
Chris Lattner0e5f4992006-12-19 21:40:18 +000071namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000072 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000075 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000076 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000078 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000079 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000080 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000081 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000082 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
Chris Lattnerdbab3862007-03-02 21:28:56 +000084 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
89 }
90
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
95
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
98
99 WorklistMap.erase(It);
100 }
101
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
104 Worklist.pop_back();
105 WorklistMap.erase(I);
106 return I;
107 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000108
Chris Lattnerdbab3862007-03-02 21:28:56 +0000109
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000114 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000117 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000118 }
119
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
122 ///
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000126 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000127 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000128
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
132 ///
133 /// Return the specified operand before it is turned into an undef.
134 ///
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
137
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000140 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
143 }
144
145 return R;
146 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000147
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000148 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000149 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000150
151 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000152
Chris Lattner97e52e42002-04-28 21:27:06 +0000153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000154 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000155 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000156 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000157 }
158
Chris Lattner28977af2004-04-05 01:30:19 +0000159 TargetData &getTargetData() const { return *TD; }
160
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
163 // Return Value:
164 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000165 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000166 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000167 //
Chris Lattner7e708292002-06-25 16:13:24 +0000168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000188 Instruction *visitFCmpInst(FCmpInst &I);
189 Instruction *visitICmpInst(ICmpInst &I);
190 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000191 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
192 Instruction *LHS,
193 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000194 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
195 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000196
Reid Spencere4d87aa2006-12-23 06:05:41 +0000197 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
198 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000199 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000200 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000201 Instruction *commonCastTransforms(CastInst &CI);
202 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000203 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000204 Instruction *visitTrunc(TruncInst &CI);
205 Instruction *visitZExt(ZExtInst &CI);
206 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000207 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000208 Instruction *visitFPExt(CastInst &CI);
209 Instruction *visitFPToUI(CastInst &CI);
210 Instruction *visitFPToSI(CastInst &CI);
211 Instruction *visitUIToFP(CastInst &CI);
212 Instruction *visitSIToFP(CastInst &CI);
213 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000214 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000215 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000216 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
217 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000218 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000219 Instruction *visitCallInst(CallInst &CI);
220 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000221 Instruction *visitPHINode(PHINode &PN);
222 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000223 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000224 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000225 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000226 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000227 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000228 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000229 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000230 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000231 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000232
233 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000234 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000235
Chris Lattner9fe38862003-06-19 17:00:31 +0000236 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000237 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000238 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000239 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000240 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
241 bool DoXform = true);
Chris Lattner9fe38862003-06-19 17:00:31 +0000242
Chris Lattner28977af2004-04-05 01:30:19 +0000243 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000244 // InsertNewInstBefore - insert an instruction New before instruction Old
245 // in the program. Add the new instruction to the worklist.
246 //
Chris Lattner955f3312004-09-28 21:48:02 +0000247 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000248 assert(New && New->getParent() == 0 &&
249 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000250 BasicBlock *BB = Old.getParent();
251 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000252 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000253 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000254 }
255
Chris Lattner0c967662004-09-24 15:21:34 +0000256 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
257 /// This also adds the cast to the worklist. Finally, this returns the
258 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000259 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
260 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000261 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000262
Chris Lattnere2ed0572006-04-06 19:19:17 +0000263 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000264 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000265
Reid Spencer17212df2006-12-12 09:18:51 +0000266 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000267 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000268 return C;
269 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000270
271 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
272 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
273 }
274
Chris Lattner0c967662004-09-24 15:21:34 +0000275
Chris Lattner8b170942002-08-09 23:47:40 +0000276 // ReplaceInstUsesWith - This method is to be used when an instruction is
277 // found to be dead, replacable with another preexisting expression. Here
278 // we add all uses of I to the worklist, replace all uses of I with the new
279 // value, then return I, so that the inst combiner will know that I was
280 // modified.
281 //
282 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000283 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000284 if (&I != V) {
285 I.replaceAllUsesWith(V);
286 return &I;
287 } else {
288 // If we are replacing the instruction with itself, this must be in a
289 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000290 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000291 return &I;
292 }
Chris Lattner8b170942002-08-09 23:47:40 +0000293 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000294
Chris Lattner6dce1a72006-02-07 06:56:34 +0000295 // UpdateValueUsesWith - This method is to be used when an value is
296 // found to be replacable with another preexisting expression or was
297 // updated. Here we add all uses of I to the worklist, replace all uses of
298 // I with the new value (unless the instruction was just updated), then
299 // return true, so that the inst combiner will know that I was modified.
300 //
301 bool UpdateValueUsesWith(Value *Old, Value *New) {
302 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
303 if (Old != New)
304 Old->replaceAllUsesWith(New);
305 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000306 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000307 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000308 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000309 return true;
310 }
311
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000312 // EraseInstFromFunction - When dealing with an instruction that has side
313 // effects or produces a void value, we can't rely on DCE to delete the
314 // instruction. Instead, visit methods should return the value returned by
315 // this function.
316 Instruction *EraseInstFromFunction(Instruction &I) {
317 assert(I.use_empty() && "Cannot erase instruction that is used!");
318 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000319 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000320 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000321 return 0; // Don't do anything with FI
322 }
323
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000324 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000325 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
326 /// InsertBefore instruction. This is specialized a bit to avoid inserting
327 /// casts that are known to not do anything...
328 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000329 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
330 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000331 Instruction *InsertBefore);
332
Reid Spencere4d87aa2006-12-23 06:05:41 +0000333 /// SimplifyCommutative - This performs a few simplifications for
334 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000335 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000336
Reid Spencere4d87aa2006-12-23 06:05:41 +0000337 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338 /// most-complex to least-complex order.
339 bool SimplifyCompare(CmpInst &I);
340
Reid Spencer2ec619a2007-03-23 21:24:59 +0000341 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
342 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000343 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
344 APInt& KnownZero, APInt& KnownOne,
345 unsigned Depth = 0);
346
Chris Lattner867b99f2006-10-05 06:55:50 +0000347 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
348 uint64_t &UndefElts, unsigned Depth = 0);
349
Chris Lattner4e998b22004-09-29 05:07:12 +0000350 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
351 // PHI node as operand #0, see if we can fold the instruction into the PHI
352 // (which is only possible if all operands to the PHI are constants).
353 Instruction *FoldOpIntoPhi(Instruction &I);
354
Chris Lattnerbac32862004-11-14 19:13:23 +0000355 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
356 // operator and they all are only used by the PHI, PHI together their
357 // inputs, and do the operation once, to the result of the PHI.
358 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000359 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
360
361
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000362 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
363 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000364
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000365 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000366 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000367 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000368 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000369 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000370 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000371 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000372 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000373 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000374
Chris Lattnerafe91a52006-06-15 19:07:26 +0000375
Reid Spencerc55b2432006-12-13 18:21:21 +0000376 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000377
378 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
379 APInt& KnownOne, unsigned Depth = 0);
380 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
381 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
382 unsigned CastOpc,
383 int &NumCastsRemoved);
384 unsigned GetOrEnforceKnownAlignment(Value *V,
385 unsigned PrefAlign = 0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000386 };
387}
388
Dan Gohman844731a2008-05-13 00:00:25 +0000389char InstCombiner::ID = 0;
390static RegisterPass<InstCombiner>
391X("instcombine", "Combine redundant instructions");
392
Chris Lattner4f98c562003-03-10 21:43:22 +0000393// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000394// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000395static unsigned getComplexity(Value *V) {
396 if (isa<Instruction>(V)) {
397 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000398 return 3;
399 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000400 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000401 if (isa<Argument>(V)) return 3;
402 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000403}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000404
Chris Lattnerc8802d22003-03-11 00:12:48 +0000405// isOnlyUse - Return true if this instruction will be deleted if we stop using
406// it.
407static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000408 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000409}
410
Chris Lattner4cb170c2004-02-23 06:38:22 +0000411// getPromotedType - Return the specified type promoted as it would be to pass
412// though a va_arg area...
413static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000414 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
415 if (ITy->getBitWidth() < 32)
416 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000417 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000418 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000419}
420
Reid Spencer3da59db2006-11-27 01:05:10 +0000421/// getBitCastOperand - If the specified operand is a CastInst or a constant
422/// expression bitcast, return the operand value, otherwise return null.
423static Value *getBitCastOperand(Value *V) {
424 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000425 return I->getOperand(0);
426 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000427 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000428 return CE->getOperand(0);
429 return 0;
430}
431
Reid Spencer3da59db2006-11-27 01:05:10 +0000432/// This function is a wrapper around CastInst::isEliminableCastPair. It
433/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000434static Instruction::CastOps
435isEliminableCastPair(
436 const CastInst *CI, ///< The first cast instruction
437 unsigned opcode, ///< The opcode of the second cast instruction
438 const Type *DstTy, ///< The target type for the second cast instruction
439 TargetData *TD ///< The target data for pointer size
440) {
441
442 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
443 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000444
Reid Spencer3da59db2006-11-27 01:05:10 +0000445 // Get the opcodes of the two Cast instructions
446 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
447 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000448
Reid Spencer3da59db2006-11-27 01:05:10 +0000449 return Instruction::CastOps(
450 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
451 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000452}
453
454/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
455/// in any code being generated. It does not require codegen if V is simple
456/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000457static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
458 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000459 if (V->getType() == Ty || isa<Constant>(V)) return false;
460
Chris Lattner01575b72006-05-25 23:24:33 +0000461 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000462 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000463 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000464 return false;
465 return true;
466}
467
468/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
469/// InsertBefore instruction. This is specialized a bit to avoid inserting
470/// casts that are known to not do anything...
471///
Reid Spencer17212df2006-12-12 09:18:51 +0000472Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
473 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000474 Instruction *InsertBefore) {
475 if (V->getType() == DestTy) return V;
476 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000477 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000478
Reid Spencer17212df2006-12-12 09:18:51 +0000479 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000480}
481
Chris Lattner4f98c562003-03-10 21:43:22 +0000482// SimplifyCommutative - This performs a few simplifications for commutative
483// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000484//
Chris Lattner4f98c562003-03-10 21:43:22 +0000485// 1. Order operands such that they are listed from right (least complex) to
486// left (most complex). This puts constants before unary operators before
487// binary operators.
488//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000489// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
490// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000491//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000492bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000493 bool Changed = false;
494 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
495 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000496
Chris Lattner4f98c562003-03-10 21:43:22 +0000497 if (!I.isAssociative()) return Changed;
498 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000499 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
500 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
501 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000502 Constant *Folded = ConstantExpr::get(I.getOpcode(),
503 cast<Constant>(I.getOperand(1)),
504 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000505 I.setOperand(0, Op->getOperand(0));
506 I.setOperand(1, Folded);
507 return true;
508 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
509 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
510 isOnlyUse(Op) && isOnlyUse(Op1)) {
511 Constant *C1 = cast<Constant>(Op->getOperand(1));
512 Constant *C2 = cast<Constant>(Op1->getOperand(1));
513
514 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000515 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000516 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
517 Op1->getOperand(0),
518 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000519 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000520 I.setOperand(0, New);
521 I.setOperand(1, Folded);
522 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000523 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000524 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000525 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000526}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000527
Reid Spencere4d87aa2006-12-23 06:05:41 +0000528/// SimplifyCompare - For a CmpInst this function just orders the operands
529/// so that theyare listed from right (least complex) to left (most complex).
530/// This puts constants before unary operators before binary operators.
531bool InstCombiner::SimplifyCompare(CmpInst &I) {
532 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
533 return false;
534 I.swapOperands();
535 // Compare instructions are not associative so there's nothing else we can do.
536 return true;
537}
538
Chris Lattner8d969642003-03-10 23:06:50 +0000539// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
540// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000541//
Chris Lattner8d969642003-03-10 23:06:50 +0000542static inline Value *dyn_castNegVal(Value *V) {
543 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000544 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000545
Chris Lattner0ce85802004-12-14 20:08:06 +0000546 // Constants can be considered to be negated values if they can be folded.
547 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
548 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000549 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000550}
551
Chris Lattner8d969642003-03-10 23:06:50 +0000552static inline Value *dyn_castNotVal(Value *V) {
553 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000554 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000555
556 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000557 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000558 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000559 return 0;
560}
561
Chris Lattnerc8802d22003-03-11 00:12:48 +0000562// dyn_castFoldableMul - If this value is a multiply that can be folded into
563// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000564// non-constant operand of the multiply, and set CST to point to the multiplier.
565// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000566//
Chris Lattner50af16a2004-11-13 19:50:12 +0000567static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000568 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000569 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000570 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000571 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000572 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000573 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000574 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000575 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000576 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000577 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000578 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000579 return I->getOperand(0);
580 }
581 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000582 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000583}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000584
Chris Lattner574da9b2005-01-13 20:14:25 +0000585/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
586/// expression, return it.
587static User *dyn_castGetElementPtr(Value *V) {
588 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
589 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
590 if (CE->getOpcode() == Instruction::GetElementPtr)
591 return cast<User>(V);
592 return false;
593}
594
Dan Gohmaneee962e2008-04-10 18:43:06 +0000595/// getOpcode - If this is an Instruction or a ConstantExpr, return the
596/// opcode value. Otherwise return UserOp1.
597static unsigned getOpcode(User *U) {
598 if (Instruction *I = dyn_cast<Instruction>(U))
599 return I->getOpcode();
600 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
601 return CE->getOpcode();
602 // Use UserOp1 to mean there's no opcode.
603 return Instruction::UserOp1;
604}
605
Reid Spencer7177c3a2007-03-25 05:33:51 +0000606/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000607static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000608 APInt Val(C->getValue());
609 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000610}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000611/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000612static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000613 APInt Val(C->getValue());
614 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000615}
616/// Add - Add two ConstantInts together
617static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
618 return ConstantInt::get(C1->getValue() + C2->getValue());
619}
620/// And - Bitwise AND two ConstantInts together
621static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
622 return ConstantInt::get(C1->getValue() & C2->getValue());
623}
624/// Subtract - Subtract one ConstantInt from another
625static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
626 return ConstantInt::get(C1->getValue() - C2->getValue());
627}
628/// Multiply - Multiply two ConstantInts together
629static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
630 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000631}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000632/// MultiplyOverflows - True if the multiply can not be expressed in an int
633/// this size.
634static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
635 uint32_t W = C1->getBitWidth();
636 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
637 if (sign) {
638 LHSExt.sext(W * 2);
639 RHSExt.sext(W * 2);
640 } else {
641 LHSExt.zext(W * 2);
642 RHSExt.zext(W * 2);
643 }
644
645 APInt MulExt = LHSExt * RHSExt;
646
647 if (sign) {
648 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
649 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
650 return MulExt.slt(Min) || MulExt.sgt(Max);
651 } else
652 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
653}
Chris Lattner955f3312004-09-28 21:48:02 +0000654
Chris Lattner68d5ff22006-02-09 07:38:58 +0000655/// ComputeMaskedBits - Determine which of the bits specified in Mask are
656/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000657/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
658/// processing.
659/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
660/// we cannot optimize based on the assumption that it is zero without changing
661/// it to be an explicit zero. If we don't change it to zero, other code could
662/// optimized based on the contradictory assumption that it is non-zero.
663/// Because instcombine aggressively folds operations with undef args anyway,
664/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000665void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
666 APInt& KnownZero, APInt& KnownOne,
667 unsigned Depth) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000668 assert(V && "No Value?");
669 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000670 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000671 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
672 "Not integer or pointer type!");
673 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
674 (!isa<IntegerType>(V->getType()) ||
675 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000676 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000677 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000678 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000679 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
680 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000681 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000682 KnownZero = ~KnownOne & Mask;
683 return;
684 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000685 // Null is all-zeros.
686 if (isa<ConstantPointerNull>(V)) {
687 KnownOne.clear();
688 KnownZero = Mask;
689 return;
690 }
691 // The address of an aligned GlobalValue has trailing zeros.
692 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
693 unsigned Align = GV->getAlignment();
694 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
695 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
696 if (Align > 0)
697 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
698 CountTrailingZeros_32(Align));
699 else
700 KnownZero.clear();
701 KnownOne.clear();
702 return;
703 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000704
Dan Gohman23e8b712008-04-28 17:02:21 +0000705 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
706
Reid Spencer3e7594f2007-03-08 01:46:38 +0000707 if (Depth == 6 || Mask == 0)
708 return; // Limit search depth.
709
Dan Gohmaneee962e2008-04-10 18:43:06 +0000710 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000711 if (!I) return;
712
713 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000714 switch (getOpcode(I)) {
715 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000716 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000717 // If either the LHS or the RHS are Zero, the result is zero.
718 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000719 APInt Mask2(Mask & ~KnownZero);
720 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000721 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
722 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
723
724 // Output known-1 bits are only known if set in both the LHS & RHS.
725 KnownOne &= KnownOne2;
726 // Output known-0 are known to be clear if zero in either the LHS | RHS.
727 KnownZero |= KnownZero2;
728 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000729 }
730 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000731 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000732 APInt Mask2(Mask & ~KnownOne);
733 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000734 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
735 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
736
737 // Output known-0 bits are only known if clear in both the LHS & RHS.
738 KnownZero &= KnownZero2;
739 // Output known-1 are known to be set if set in either the LHS | RHS.
740 KnownOne |= KnownOne2;
741 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000742 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000743 case Instruction::Xor: {
744 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
745 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
746 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
747 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
748
749 // Output known-0 bits are known if clear or set in both the LHS & RHS.
750 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
751 // Output known-1 are known to be set if set in only one of the LHS, RHS.
752 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
753 KnownZero = KnownZeroOut;
754 return;
755 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000756 case Instruction::Mul: {
757 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
758 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
759 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
760 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
761 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
762
763 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman23e8b712008-04-28 17:02:21 +0000764 // Also compute a conserative estimate for high known-0 bits.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000765 // More trickiness is possible, but this is sufficient for the
766 // interesting case of alignment computation.
767 KnownOne.clear();
768 unsigned TrailZ = KnownZero.countTrailingOnes() +
769 KnownZero2.countTrailingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +0000770 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman42ac9292008-05-07 00:35:55 +0000771 KnownZero2.countLeadingOnes(),
772 BitWidth) - BitWidth;
Dan Gohman23e8b712008-04-28 17:02:21 +0000773
Dan Gohmaneee962e2008-04-10 18:43:06 +0000774 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000775 LeadZ = std::min(LeadZ, BitWidth);
776 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
777 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000778 KnownZero &= Mask;
779 return;
780 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000781 case Instruction::UDiv: {
782 // For the purposes of computing leading zeros we can conservatively
783 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1d9cd502008-05-02 21:30:02 +0000784 // be less than the denominator.
Dan Gohman23e8b712008-04-28 17:02:21 +0000785 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
786 ComputeMaskedBits(I->getOperand(0),
787 AllOnes, KnownZero2, KnownOne2, Depth+1);
788 unsigned LeadZ = KnownZero2.countLeadingOnes();
789
790 KnownOne2.clear();
791 KnownZero2.clear();
792 ComputeMaskedBits(I->getOperand(1),
793 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1d9cd502008-05-02 21:30:02 +0000794 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
795 if (RHSUnknownLeadingOnes != BitWidth)
796 LeadZ = std::min(BitWidth,
797 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000798
799 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
800 return;
801 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000802 case Instruction::Select:
803 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
804 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
805 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
806 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
807
808 // Only known if known in both the LHS and RHS.
809 KnownOne &= KnownOne2;
810 KnownZero &= KnownZero2;
811 return;
812 case Instruction::FPTrunc:
813 case Instruction::FPExt:
814 case Instruction::FPToUI:
815 case Instruction::FPToSI:
816 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000817 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000818 return; // Can't work with floating point.
819 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000820 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000821 // We can't handle these if we don't know the pointer size.
822 if (!TD) return;
823 // Fall through and handle them the same as zext/trunc.
824 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000825 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000826 // All these have integer operands
Dan Gohmaneee962e2008-04-10 18:43:06 +0000827 const Type *SrcTy = I->getOperand(0)->getType();
828 uint32_t SrcBitWidth = TD ?
829 TD->getTypeSizeInBits(SrcTy) :
830 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000831 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000832 MaskIn.zextOrTrunc(SrcBitWidth);
833 KnownZero.zextOrTrunc(SrcBitWidth);
834 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000835 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000836 KnownZero.zextOrTrunc(BitWidth);
837 KnownOne.zextOrTrunc(BitWidth);
838 // Any top bits are known to be zero.
839 if (BitWidth > SrcBitWidth)
840 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000841 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000842 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000843 case Instruction::BitCast: {
844 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000845 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000846 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
847 return;
848 }
849 break;
850 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000851 case Instruction::SExt: {
852 // Compute the bits in the result that are not present in the input.
853 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000854 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000855
Zhou Shengaa305ab2007-03-28 02:19:03 +0000856 APInt MaskIn(Mask);
857 MaskIn.trunc(SrcBitWidth);
858 KnownZero.trunc(SrcBitWidth);
859 KnownOne.trunc(SrcBitWidth);
860 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000861 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000862 KnownZero.zext(BitWidth);
863 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000864
865 // If the sign bit of the input is known set or clear, then we know the
866 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000867 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000868 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000869 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000870 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000871 return;
872 }
873 case Instruction::Shl:
874 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
875 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000876 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000877 APInt Mask2(Mask.lshr(ShiftAmt));
878 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000879 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000880 KnownZero <<= ShiftAmt;
881 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000882 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000883 return;
884 }
885 break;
886 case Instruction::LShr:
887 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
888 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
889 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000890 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000891
892 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000893 APInt Mask2(Mask.shl(ShiftAmt));
894 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000895 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
896 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
897 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000898 // high bits known zero.
899 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000900 return;
901 }
902 break;
903 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000904 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000905 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
906 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000907 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000908
909 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000910 APInt Mask2(Mask.shl(ShiftAmt));
911 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000912 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
913 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
914 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
915
Zhou Shengaa305ab2007-03-28 02:19:03 +0000916 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
917 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000918 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000919 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000920 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000921 return;
922 }
923 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000924 case Instruction::Sub: {
925 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
926 // We know that the top bits of C-X are clear if X contains less bits
927 // than C (i.e. no wrap-around can happen). For example, 20-X is
928 // positive if we can prove that X is >= 0 and < 16.
929 if (!CLHS->getValue().isNegative()) {
930 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
931 // NLZ can't be BitWidth with no sign bit
932 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000933 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
934 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000935
Dan Gohman23e8b712008-04-28 17:02:21 +0000936 // If all of the MaskV bits are known to be zero, then we know the
937 // output top bits are zero, because we now know that the output is
938 // from [0-C].
939 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000940 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
941 // Top bits known zero.
942 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000943 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000944 }
945 }
946 }
947 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000948 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000949 // Output known-0 bits are known if clear or set in both the low clear bits
950 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
951 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000952 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
953 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
954 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
955 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
956
957 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
958 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
959 KnownZeroOut = std::min(KnownZeroOut,
960 KnownZero2.countTrailingOnes());
961
962 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000963 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000964 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000965 case Instruction::SRem:
966 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
967 APInt RA = Rem->getValue();
968 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000969 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000970 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
971 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
972
973 // The sign of a remainder is equal to the sign of the first
974 // operand (zero being positive).
975 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
976 KnownZero2 |= ~LowBits;
977 else if (KnownOne2[BitWidth-1])
978 KnownOne2 |= ~LowBits;
979
980 KnownZero |= KnownZero2 & Mask;
981 KnownOne |= KnownOne2 & Mask;
982
983 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
984 }
985 }
986 break;
Dan Gohman23e8b712008-04-28 17:02:21 +0000987 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000988 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
989 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +0000990 if (RA.isPowerOf2()) {
991 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000992 APInt Mask2 = LowBits & Mask;
993 KnownZero |= ~LowBits & Mask;
994 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
995 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +0000996 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000997 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000998 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000999
1000 // Since the result is less than or equal to either operand, any leading
1001 // zero bits in either operand must also exist in the result.
1002 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1003 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1004 Depth+1);
1005 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1006 Depth+1);
1007
1008 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1009 KnownZero2.countLeadingOnes());
1010 KnownOne.clear();
1011 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001012 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001013 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001014
1015 case Instruction::Alloca:
1016 case Instruction::Malloc: {
1017 AllocationInst *AI = cast<AllocationInst>(V);
1018 unsigned Align = AI->getAlignment();
1019 if (Align == 0 && TD) {
1020 if (isa<AllocaInst>(AI))
1021 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1022 else if (isa<MallocInst>(AI)) {
1023 // Malloc returns maximally aligned memory.
1024 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1025 Align =
1026 std::max(Align,
1027 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1028 Align =
1029 std::max(Align,
1030 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1031 }
1032 }
1033
1034 if (Align > 0)
1035 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1036 CountTrailingZeros_32(Align));
1037 break;
1038 }
1039 case Instruction::GetElementPtr: {
1040 // Analyze all of the subscripts of this getelementptr instruction
1041 // to determine if we can prove known low zero bits.
1042 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1043 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1044 ComputeMaskedBits(I->getOperand(0), LocalMask,
1045 LocalKnownZero, LocalKnownOne, Depth+1);
1046 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1047
1048 gep_type_iterator GTI = gep_type_begin(I);
1049 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1050 Value *Index = I->getOperand(i);
1051 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1052 // Handle struct member offset arithmetic.
1053 if (!TD) return;
1054 const StructLayout *SL = TD->getStructLayout(STy);
1055 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1056 uint64_t Offset = SL->getElementOffset(Idx);
1057 TrailZ = std::min(TrailZ,
1058 CountTrailingZeros_64(Offset));
1059 } else {
1060 // Handle array index arithmetic.
1061 const Type *IndexedTy = GTI.getIndexedType();
1062 if (!IndexedTy->isSized()) return;
1063 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1064 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1065 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1066 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1067 ComputeMaskedBits(Index, LocalMask,
1068 LocalKnownZero, LocalKnownOne, Depth+1);
1069 TrailZ = std::min(TrailZ,
1070 CountTrailingZeros_64(TypeSize) +
1071 LocalKnownZero.countTrailingOnes());
1072 }
1073 }
1074
1075 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1076 break;
1077 }
1078 case Instruction::PHI: {
1079 PHINode *P = cast<PHINode>(I);
1080 // Handle the case of a simple two-predecessor recurrence PHI.
1081 // There's a lot more that could theoretically be done here, but
1082 // this is sufficient to catch some interesting cases.
1083 if (P->getNumIncomingValues() == 2) {
1084 for (unsigned i = 0; i != 2; ++i) {
1085 Value *L = P->getIncomingValue(i);
1086 Value *R = P->getIncomingValue(!i);
1087 User *LU = dyn_cast<User>(L);
1088 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1089 // Check for operations that have the property that if
1090 // both their operands have low zero bits, the result
1091 // will have low zero bits.
1092 if (Opcode == Instruction::Add ||
1093 Opcode == Instruction::Sub ||
1094 Opcode == Instruction::And ||
1095 Opcode == Instruction::Or ||
1096 Opcode == Instruction::Mul) {
1097 Value *LL = LU->getOperand(0);
1098 Value *LR = LU->getOperand(1);
1099 // Find a recurrence.
1100 if (LL == I)
1101 L = LR;
1102 else if (LR == I)
1103 L = LL;
1104 else
1105 break;
1106 // Ok, we have a PHI of the form L op= R. Check for low
1107 // zero bits.
1108 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1109 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1110 Mask2 = APInt::getLowBitsSet(BitWidth,
1111 KnownZero2.countTrailingOnes());
1112 KnownOne2.clear();
1113 KnownZero2.clear();
1114 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1115 KnownZero = Mask &
1116 APInt::getLowBitsSet(BitWidth,
1117 KnownZero2.countTrailingOnes());
1118 break;
1119 }
1120 }
1121 }
1122 break;
1123 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001124 case Instruction::Call:
1125 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1126 switch (II->getIntrinsicID()) {
1127 default: break;
1128 case Intrinsic::ctpop:
1129 case Intrinsic::ctlz:
1130 case Intrinsic::cttz: {
1131 unsigned LowBits = Log2_32(BitWidth)+1;
1132 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1133 break;
1134 }
1135 }
1136 }
1137 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001138 }
1139}
1140
Reid Spencere7816b52007-03-08 01:52:58 +00001141/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1142/// this predicate to simplify operations downstream. Mask is known to be zero
1143/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001144bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1145 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001146 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001147 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1148 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1149 return (KnownZero & Mask) == Mask;
1150}
1151
Chris Lattner255d8912006-02-11 09:31:47 +00001152/// ShrinkDemandedConstant - Check to see if the specified operand of the
1153/// specified instruction is a constant integer. If so, check to see if there
1154/// are any bits set in the constant that are not demanded. If so, shrink the
1155/// constant and return true.
1156static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001157 APInt Demanded) {
1158 assert(I && "No instruction?");
1159 assert(OpNo < I->getNumOperands() && "Operand index too large");
1160
1161 // If the operand is not a constant integer, nothing to do.
1162 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1163 if (!OpC) return false;
1164
1165 // If there are no bits set that aren't demanded, nothing to do.
1166 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1167 if ((~Demanded & OpC->getValue()) == 0)
1168 return false;
1169
1170 // This instruction is producing bits that are not demanded. Shrink the RHS.
1171 Demanded &= OpC->getValue();
1172 I->setOperand(OpNo, ConstantInt::get(Demanded));
1173 return true;
1174}
1175
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001176// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1177// set of known zero and one bits, compute the maximum and minimum values that
1178// could have the specified known zero and known one bits, returning them in
1179// min/max.
1180static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001181 const APInt& KnownZero,
1182 const APInt& KnownOne,
1183 APInt& Min, APInt& Max) {
1184 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1185 assert(KnownZero.getBitWidth() == BitWidth &&
1186 KnownOne.getBitWidth() == BitWidth &&
1187 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1188 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001189 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001190
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001191 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1192 // bit if it is unknown.
1193 Min = KnownOne;
1194 Max = KnownOne|UnknownBits;
1195
Zhou Sheng4acf1552007-03-28 05:15:57 +00001196 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001197 Min.set(BitWidth-1);
1198 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001199 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001200}
1201
1202// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1203// a set of known zero and one bits, compute the maximum and minimum values that
1204// could have the specified known zero and known one bits, returning them in
1205// min/max.
1206static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001207 const APInt &KnownZero,
1208 const APInt &KnownOne,
1209 APInt &Min, APInt &Max) {
1210 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001211 assert(KnownZero.getBitWidth() == BitWidth &&
1212 KnownOne.getBitWidth() == BitWidth &&
1213 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1214 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001215 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001216
1217 // The minimum value is when the unknown bits are all zeros.
1218 Min = KnownOne;
1219 // The maximum value is when the unknown bits are all ones.
1220 Max = KnownOne|UnknownBits;
1221}
Chris Lattner255d8912006-02-11 09:31:47 +00001222
Reid Spencer8cb68342007-03-12 17:25:59 +00001223/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1224/// value based on the demanded bits. When this function is called, it is known
1225/// that only the bits set in DemandedMask of the result of V are ever used
1226/// downstream. Consequently, depending on the mask and V, it may be possible
1227/// to replace V with a constant or one of its operands. In such cases, this
1228/// function does the replacement and returns true. In all other cases, it
1229/// returns false after analyzing the expression and setting KnownOne and known
1230/// to be one in the expression. KnownZero contains all the bits that are known
1231/// to be zero in the expression. These are provided to potentially allow the
1232/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1233/// the expression. KnownOne and KnownZero always follow the invariant that
1234/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1235/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1236/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1237/// and KnownOne must all be the same.
1238bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1239 APInt& KnownZero, APInt& KnownOne,
1240 unsigned Depth) {
1241 assert(V != 0 && "Null pointer of Value???");
1242 assert(Depth <= 6 && "Limit Search Depth");
1243 uint32_t BitWidth = DemandedMask.getBitWidth();
1244 const IntegerType *VTy = cast<IntegerType>(V->getType());
1245 assert(VTy->getBitWidth() == BitWidth &&
1246 KnownZero.getBitWidth() == BitWidth &&
1247 KnownOne.getBitWidth() == BitWidth &&
1248 "Value *V, DemandedMask, KnownZero and KnownOne \
1249 must have same BitWidth");
1250 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1251 // We know all of the bits for a constant!
1252 KnownOne = CI->getValue() & DemandedMask;
1253 KnownZero = ~KnownOne & DemandedMask;
1254 return false;
1255 }
1256
Zhou Sheng96704452007-03-14 03:21:24 +00001257 KnownZero.clear();
1258 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 if (!V->hasOneUse()) { // Other users may use these bits.
1260 if (Depth != 0) { // Not at the root.
1261 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1262 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1263 return false;
1264 }
1265 // If this is the root being simplified, allow it to have multiple uses,
1266 // just set the DemandedMask to all bits.
1267 DemandedMask = APInt::getAllOnesValue(BitWidth);
1268 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1269 if (V != UndefValue::get(VTy))
1270 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1271 return false;
1272 } else if (Depth == 6) { // Limit search depth.
1273 return false;
1274 }
1275
1276 Instruction *I = dyn_cast<Instruction>(V);
1277 if (!I) return false; // Only analyze instructions.
1278
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1280 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1281 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001282 default:
1283 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1284 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 case Instruction::And:
1286 // If either the LHS or the RHS are Zero, the result is zero.
1287 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1288 RHSKnownZero, RHSKnownOne, Depth+1))
1289 return true;
1290 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1291 "Bits known to be one AND zero?");
1292
1293 // If something is known zero on the RHS, the bits aren't demanded on the
1294 // LHS.
1295 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1296 LHSKnownZero, LHSKnownOne, Depth+1))
1297 return true;
1298 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1299 "Bits known to be one AND zero?");
1300
1301 // If all of the demanded bits are known 1 on one side, return the other.
1302 // These bits cannot contribute to the result of the 'and'.
1303 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1304 (DemandedMask & ~LHSKnownZero))
1305 return UpdateValueUsesWith(I, I->getOperand(0));
1306 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1307 (DemandedMask & ~RHSKnownZero))
1308 return UpdateValueUsesWith(I, I->getOperand(1));
1309
1310 // If all of the demanded bits in the inputs are known zeros, return zero.
1311 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1312 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1313
1314 // If the RHS is a constant, see if we can simplify it.
1315 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1316 return UpdateValueUsesWith(I, I);
1317
1318 // Output known-1 bits are only known if set in both the LHS & RHS.
1319 RHSKnownOne &= LHSKnownOne;
1320 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1321 RHSKnownZero |= LHSKnownZero;
1322 break;
1323 case Instruction::Or:
1324 // If either the LHS or the RHS are One, the result is One.
1325 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1326 RHSKnownZero, RHSKnownOne, Depth+1))
1327 return true;
1328 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1329 "Bits known to be one AND zero?");
1330 // If something is known one on the RHS, the bits aren't demanded on the
1331 // LHS.
1332 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1333 LHSKnownZero, LHSKnownOne, Depth+1))
1334 return true;
1335 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1336 "Bits known to be one AND zero?");
1337
1338 // If all of the demanded bits are known zero on one side, return the other.
1339 // These bits cannot contribute to the result of the 'or'.
1340 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1341 (DemandedMask & ~LHSKnownOne))
1342 return UpdateValueUsesWith(I, I->getOperand(0));
1343 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1344 (DemandedMask & ~RHSKnownOne))
1345 return UpdateValueUsesWith(I, I->getOperand(1));
1346
1347 // If all of the potentially set bits on one side are known to be set on
1348 // the other side, just use the 'other' side.
1349 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1350 (DemandedMask & (~RHSKnownZero)))
1351 return UpdateValueUsesWith(I, I->getOperand(0));
1352 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1353 (DemandedMask & (~LHSKnownZero)))
1354 return UpdateValueUsesWith(I, I->getOperand(1));
1355
1356 // If the RHS is a constant, see if we can simplify it.
1357 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1358 return UpdateValueUsesWith(I, I);
1359
1360 // Output known-0 bits are only known if clear in both the LHS & RHS.
1361 RHSKnownZero &= LHSKnownZero;
1362 // Output known-1 are known to be set if set in either the LHS | RHS.
1363 RHSKnownOne |= LHSKnownOne;
1364 break;
1365 case Instruction::Xor: {
1366 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1367 RHSKnownZero, RHSKnownOne, Depth+1))
1368 return true;
1369 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1370 "Bits known to be one AND zero?");
1371 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1372 LHSKnownZero, LHSKnownOne, Depth+1))
1373 return true;
1374 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1375 "Bits known to be one AND zero?");
1376
1377 // If all of the demanded bits are known zero on one side, return the other.
1378 // These bits cannot contribute to the result of the 'xor'.
1379 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1380 return UpdateValueUsesWith(I, I->getOperand(0));
1381 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1382 return UpdateValueUsesWith(I, I->getOperand(1));
1383
1384 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1385 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1386 (RHSKnownOne & LHSKnownOne);
1387 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1388 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1389 (RHSKnownOne & LHSKnownZero);
1390
1391 // If all of the demanded bits are known to be zero on one side or the
1392 // other, turn this into an *inclusive* or.
1393 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1394 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1395 Instruction *Or =
1396 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1397 I->getName());
1398 InsertNewInstBefore(Or, *I);
1399 return UpdateValueUsesWith(I, Or);
1400 }
1401
1402 // If all of the demanded bits on one side are known, and all of the set
1403 // bits on that side are also known to be set on the other side, turn this
1404 // into an AND, as we know the bits will be cleared.
1405 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1406 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1407 // all known
1408 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1409 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1410 Instruction *And =
1411 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1412 InsertNewInstBefore(And, *I);
1413 return UpdateValueUsesWith(I, And);
1414 }
1415 }
1416
1417 // If the RHS is a constant, see if we can simplify it.
1418 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1419 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1420 return UpdateValueUsesWith(I, I);
1421
1422 RHSKnownZero = KnownZeroOut;
1423 RHSKnownOne = KnownOneOut;
1424 break;
1425 }
1426 case Instruction::Select:
1427 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1428 RHSKnownZero, RHSKnownOne, Depth+1))
1429 return true;
1430 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1431 LHSKnownZero, LHSKnownOne, Depth+1))
1432 return true;
1433 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1434 "Bits known to be one AND zero?");
1435 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1436 "Bits known to be one AND zero?");
1437
1438 // If the operands are constants, see if we can simplify them.
1439 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1440 return UpdateValueUsesWith(I, I);
1441 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1442 return UpdateValueUsesWith(I, I);
1443
1444 // Only known if known in both the LHS and RHS.
1445 RHSKnownOne &= LHSKnownOne;
1446 RHSKnownZero &= LHSKnownZero;
1447 break;
1448 case Instruction::Trunc: {
1449 uint32_t truncBf =
1450 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001451 DemandedMask.zext(truncBf);
1452 RHSKnownZero.zext(truncBf);
1453 RHSKnownOne.zext(truncBf);
1454 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1455 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001456 return true;
1457 DemandedMask.trunc(BitWidth);
1458 RHSKnownZero.trunc(BitWidth);
1459 RHSKnownOne.trunc(BitWidth);
1460 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1461 "Bits known to be one AND zero?");
1462 break;
1463 }
1464 case Instruction::BitCast:
1465 if (!I->getOperand(0)->getType()->isInteger())
1466 return false;
1467
1468 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1469 RHSKnownZero, RHSKnownOne, Depth+1))
1470 return true;
1471 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1472 "Bits known to be one AND zero?");
1473 break;
1474 case Instruction::ZExt: {
1475 // Compute the bits in the result that are not present in the input.
1476 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001477 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001478
Zhou Shengd48653a2007-03-29 04:45:55 +00001479 DemandedMask.trunc(SrcBitWidth);
1480 RHSKnownZero.trunc(SrcBitWidth);
1481 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001482 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1483 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001484 return true;
1485 DemandedMask.zext(BitWidth);
1486 RHSKnownZero.zext(BitWidth);
1487 RHSKnownOne.zext(BitWidth);
1488 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1489 "Bits known to be one AND zero?");
1490 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001491 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001492 break;
1493 }
1494 case Instruction::SExt: {
1495 // Compute the bits in the result that are not present in the input.
1496 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001497 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001498
Reid Spencer8cb68342007-03-12 17:25:59 +00001499 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001500 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001501
Zhou Sheng01542f32007-03-29 02:26:30 +00001502 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001503 // If any of the sign extended bits are demanded, we know that the sign
1504 // bit is demanded.
1505 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001506 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001507
Zhou Shengd48653a2007-03-29 04:45:55 +00001508 InputDemandedBits.trunc(SrcBitWidth);
1509 RHSKnownZero.trunc(SrcBitWidth);
1510 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001511 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1512 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001513 return true;
1514 InputDemandedBits.zext(BitWidth);
1515 RHSKnownZero.zext(BitWidth);
1516 RHSKnownOne.zext(BitWidth);
1517 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1518 "Bits known to be one AND zero?");
1519
1520 // If the sign bit of the input is known set or clear, then we know the
1521 // top bits of the result.
1522
1523 // If the input sign bit is known zero, or if the NewBits are not demanded
1524 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001525 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001526 {
1527 // Convert to ZExt cast
1528 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1529 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001530 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001531 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001532 }
1533 break;
1534 }
1535 case Instruction::Add: {
1536 // Figure out what the input bits are. If the top bits of the and result
1537 // are not demanded, then the add doesn't demand them from its input
1538 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001539 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001540
1541 // If there is a constant on the RHS, there are a variety of xformations
1542 // we can do.
1543 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1544 // If null, this should be simplified elsewhere. Some of the xforms here
1545 // won't work if the RHS is zero.
1546 if (RHS->isZero())
1547 break;
1548
1549 // If the top bit of the output is demanded, demand everything from the
1550 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001551 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001552
1553 // Find information about known zero/one bits in the input.
1554 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1555 LHSKnownZero, LHSKnownOne, Depth+1))
1556 return true;
1557
1558 // If the RHS of the add has bits set that can't affect the input, reduce
1559 // the constant.
1560 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1561 return UpdateValueUsesWith(I, I);
1562
1563 // Avoid excess work.
1564 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1565 break;
1566
1567 // Turn it into OR if input bits are zero.
1568 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1569 Instruction *Or =
1570 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1571 I->getName());
1572 InsertNewInstBefore(Or, *I);
1573 return UpdateValueUsesWith(I, Or);
1574 }
1575
1576 // We can say something about the output known-zero and known-one bits,
1577 // depending on potential carries from the input constant and the
1578 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1579 // bits set and the RHS constant is 0x01001, then we know we have a known
1580 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1581
1582 // To compute this, we first compute the potential carry bits. These are
1583 // the bits which may be modified. I'm not aware of a better way to do
1584 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001585 const APInt& RHSVal = RHS->getValue();
1586 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001587
1588 // Now that we know which bits have carries, compute the known-1/0 sets.
1589
1590 // Bits are known one if they are known zero in one operand and one in the
1591 // other, and there is no input carry.
1592 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1593 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1594
1595 // Bits are known zero if they are known zero in both operands and there
1596 // is no input carry.
1597 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1598 } else {
1599 // If the high-bits of this ADD are not demanded, then it does not demand
1600 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001601 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001602 // Right fill the mask of bits for this ADD to demand the most
1603 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001604 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001605 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1606 LHSKnownZero, LHSKnownOne, Depth+1))
1607 return true;
1608 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1609 LHSKnownZero, LHSKnownOne, Depth+1))
1610 return true;
1611 }
1612 }
1613 break;
1614 }
1615 case Instruction::Sub:
1616 // If the high-bits of this SUB are not demanded, then it does not demand
1617 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001618 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001619 // Right fill the mask of bits for this SUB to demand the most
1620 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001621 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001622 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001623 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1624 LHSKnownZero, LHSKnownOne, Depth+1))
1625 return true;
1626 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1627 LHSKnownZero, LHSKnownOne, Depth+1))
1628 return true;
1629 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001630 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1631 // the known zeros and ones.
1632 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001633 break;
1634 case Instruction::Shl:
1635 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001636 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001637 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1638 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001639 RHSKnownZero, RHSKnownOne, Depth+1))
1640 return true;
1641 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1642 "Bits known to be one AND zero?");
1643 RHSKnownZero <<= ShiftAmt;
1644 RHSKnownOne <<= ShiftAmt;
1645 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001646 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001647 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001648 }
1649 break;
1650 case Instruction::LShr:
1651 // For a logical shift right
1652 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001653 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001654
Reid Spencer8cb68342007-03-12 17:25:59 +00001655 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001656 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1657 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001658 RHSKnownZero, RHSKnownOne, Depth+1))
1659 return true;
1660 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1661 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001662 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1663 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001664 if (ShiftAmt) {
1665 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001666 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001667 RHSKnownZero |= HighBits; // high bits known zero.
1668 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001669 }
1670 break;
1671 case Instruction::AShr:
1672 // If this is an arithmetic shift right and only the low-bit is set, we can
1673 // always convert this into a logical shr, even if the shift amount is
1674 // variable. The low bit of the shift cannot be an input sign bit unless
1675 // the shift amount is >= the size of the datatype, which is undefined.
1676 if (DemandedMask == 1) {
1677 // Perform the logical shift right.
1678 Value *NewVal = BinaryOperator::createLShr(
1679 I->getOperand(0), I->getOperand(1), I->getName());
1680 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1681 return UpdateValueUsesWith(I, NewVal);
1682 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001683
1684 // If the sign bit is the only bit demanded by this ashr, then there is no
1685 // need to do it, the shift doesn't change the high bit.
1686 if (DemandedMask.isSignBit())
1687 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001688
1689 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001690 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001691
Reid Spencer8cb68342007-03-12 17:25:59 +00001692 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001693 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001694 // If any of the "high bits" are demanded, we should set the sign bit as
1695 // demanded.
1696 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1697 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001698 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001699 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001700 RHSKnownZero, RHSKnownOne, Depth+1))
1701 return true;
1702 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1703 "Bits known to be one AND zero?");
1704 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001705 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001706 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1707 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1708
1709 // Handle the sign bits.
1710 APInt SignBit(APInt::getSignBit(BitWidth));
1711 // Adjust to where it is now in the mask.
1712 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1713
1714 // If the input sign bit is known to be zero, or if none of the top bits
1715 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001716 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001717 (HighBits & ~DemandedMask) == HighBits) {
1718 // Perform the logical shift right.
1719 Value *NewVal = BinaryOperator::createLShr(
1720 I->getOperand(0), SA, I->getName());
1721 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1722 return UpdateValueUsesWith(I, NewVal);
1723 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1724 RHSKnownOne |= HighBits;
1725 }
1726 }
1727 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001728 case Instruction::SRem:
1729 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1730 APInt RA = Rem->getValue();
1731 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001732 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001733 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1734 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1735 LHSKnownZero, LHSKnownOne, Depth+1))
1736 return true;
1737
1738 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1739 LHSKnownZero |= ~LowBits;
1740 else if (LHSKnownOne[BitWidth-1])
1741 LHSKnownOne |= ~LowBits;
1742
1743 KnownZero |= LHSKnownZero & DemandedMask;
1744 KnownOne |= LHSKnownOne & DemandedMask;
1745
1746 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1747 }
1748 }
1749 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001750 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001751 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1752 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001753 if (RA.isPowerOf2()) {
1754 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001755 APInt Mask2 = LowBits & DemandedMask;
1756 KnownZero |= ~LowBits & DemandedMask;
1757 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1758 KnownZero, KnownOne, Depth+1))
1759 return true;
1760
1761 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001762 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001763 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001764 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001765
1766 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1767 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001768 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1769 KnownZero2, KnownOne2, Depth+1))
1770 return true;
1771
Dan Gohman23e8b712008-04-28 17:02:21 +00001772 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001773 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001774 KnownZero2, KnownOne2, Depth+1))
1775 return true;
1776
1777 Leaders = std::max(Leaders,
1778 KnownZero2.countLeadingOnes());
1779 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001780 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001781 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001782 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001783
1784 // If the client is only demanding bits that we know, return the known
1785 // constant.
1786 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1787 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1788 return false;
1789}
1790
Chris Lattner867b99f2006-10-05 06:55:50 +00001791
1792/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1793/// 64 or fewer elements. DemandedElts contains the set of elements that are
1794/// actually used by the caller. This method analyzes which elements of the
1795/// operand are undef and returns that information in UndefElts.
1796///
1797/// If the information about demanded elements can be used to simplify the
1798/// operation, the operation is simplified, then the resultant value is
1799/// returned. This returns null if no change was made.
1800Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1801 uint64_t &UndefElts,
1802 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001803 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001804 assert(VWidth <= 64 && "Vector too wide to analyze!");
1805 uint64_t EltMask = ~0ULL >> (64-VWidth);
1806 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1807 "Invalid DemandedElts!");
1808
1809 if (isa<UndefValue>(V)) {
1810 // If the entire vector is undefined, just return this info.
1811 UndefElts = EltMask;
1812 return 0;
1813 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1814 UndefElts = EltMask;
1815 return UndefValue::get(V->getType());
1816 }
1817
1818 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001819 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1820 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001821 Constant *Undef = UndefValue::get(EltTy);
1822
1823 std::vector<Constant*> Elts;
1824 for (unsigned i = 0; i != VWidth; ++i)
1825 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1826 Elts.push_back(Undef);
1827 UndefElts |= (1ULL << i);
1828 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1829 Elts.push_back(Undef);
1830 UndefElts |= (1ULL << i);
1831 } else { // Otherwise, defined.
1832 Elts.push_back(CP->getOperand(i));
1833 }
1834
1835 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001836 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001837 return NewCP != CP ? NewCP : 0;
1838 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001839 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001840 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001841 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001842 Constant *Zero = Constant::getNullValue(EltTy);
1843 Constant *Undef = UndefValue::get(EltTy);
1844 std::vector<Constant*> Elts;
1845 for (unsigned i = 0; i != VWidth; ++i)
1846 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1847 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001848 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001849 }
1850
1851 if (!V->hasOneUse()) { // Other users may use these bits.
1852 if (Depth != 0) { // Not at the root.
1853 // TODO: Just compute the UndefElts information recursively.
1854 return false;
1855 }
1856 return false;
1857 } else if (Depth == 10) { // Limit search depth.
1858 return false;
1859 }
1860
1861 Instruction *I = dyn_cast<Instruction>(V);
1862 if (!I) return false; // Only analyze instructions.
1863
1864 bool MadeChange = false;
1865 uint64_t UndefElts2;
1866 Value *TmpV;
1867 switch (I->getOpcode()) {
1868 default: break;
1869
1870 case Instruction::InsertElement: {
1871 // If this is a variable index, we don't know which element it overwrites.
1872 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001873 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001874 if (Idx == 0) {
1875 // Note that we can't propagate undef elt info, because we don't know
1876 // which elt is getting updated.
1877 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1878 UndefElts2, Depth+1);
1879 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1880 break;
1881 }
1882
1883 // If this is inserting an element that isn't demanded, remove this
1884 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001885 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001886 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1887 return AddSoonDeadInstToWorklist(*I, 0);
1888
1889 // Otherwise, the element inserted overwrites whatever was there, so the
1890 // input demanded set is simpler than the output set.
1891 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1892 DemandedElts & ~(1ULL << IdxNo),
1893 UndefElts, Depth+1);
1894 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1895
1896 // The inserted element is defined.
1897 UndefElts |= 1ULL << IdxNo;
1898 break;
1899 }
Chris Lattner69878332007-04-14 22:29:23 +00001900 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001901 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001902 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1903 if (!VTy) break;
1904 unsigned InVWidth = VTy->getNumElements();
1905 uint64_t InputDemandedElts = 0;
1906 unsigned Ratio;
1907
1908 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001909 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001910 // elements as are demanded of us.
1911 Ratio = 1;
1912 InputDemandedElts = DemandedElts;
1913 } else if (VWidth > InVWidth) {
1914 // Untested so far.
1915 break;
1916
1917 // If there are more elements in the result than there are in the source,
1918 // then an input element is live if any of the corresponding output
1919 // elements are live.
1920 Ratio = VWidth/InVWidth;
1921 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1922 if (DemandedElts & (1ULL << OutIdx))
1923 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1924 }
1925 } else {
1926 // Untested so far.
1927 break;
1928
1929 // If there are more elements in the source than there are in the result,
1930 // then an input element is live if the corresponding output element is
1931 // live.
1932 Ratio = InVWidth/VWidth;
1933 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1934 if (DemandedElts & (1ULL << InIdx/Ratio))
1935 InputDemandedElts |= 1ULL << InIdx;
1936 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001937
Chris Lattner69878332007-04-14 22:29:23 +00001938 // div/rem demand all inputs, because they don't want divide by zero.
1939 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1940 UndefElts2, Depth+1);
1941 if (TmpV) {
1942 I->setOperand(0, TmpV);
1943 MadeChange = true;
1944 }
1945
1946 UndefElts = UndefElts2;
1947 if (VWidth > InVWidth) {
1948 assert(0 && "Unimp");
1949 // If there are more elements in the result than there are in the source,
1950 // then an output element is undef if the corresponding input element is
1951 // undef.
1952 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1953 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1954 UndefElts |= 1ULL << OutIdx;
1955 } else if (VWidth < InVWidth) {
1956 assert(0 && "Unimp");
1957 // If there are more elements in the source than there are in the result,
1958 // then a result element is undef if all of the corresponding input
1959 // elements are undef.
1960 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1961 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1962 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1963 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1964 }
1965 break;
1966 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001967 case Instruction::And:
1968 case Instruction::Or:
1969 case Instruction::Xor:
1970 case Instruction::Add:
1971 case Instruction::Sub:
1972 case Instruction::Mul:
1973 // div/rem demand all inputs, because they don't want divide by zero.
1974 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1975 UndefElts, Depth+1);
1976 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1977 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1978 UndefElts2, Depth+1);
1979 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1980
1981 // Output elements are undefined if both are undefined. Consider things
1982 // like undef&0. The result is known zero, not undef.
1983 UndefElts &= UndefElts2;
1984 break;
1985
1986 case Instruction::Call: {
1987 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1988 if (!II) break;
1989 switch (II->getIntrinsicID()) {
1990 default: break;
1991
1992 // Binary vector operations that work column-wise. A dest element is a
1993 // function of the corresponding input elements from the two inputs.
1994 case Intrinsic::x86_sse_sub_ss:
1995 case Intrinsic::x86_sse_mul_ss:
1996 case Intrinsic::x86_sse_min_ss:
1997 case Intrinsic::x86_sse_max_ss:
1998 case Intrinsic::x86_sse2_sub_sd:
1999 case Intrinsic::x86_sse2_mul_sd:
2000 case Intrinsic::x86_sse2_min_sd:
2001 case Intrinsic::x86_sse2_max_sd:
2002 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2003 UndefElts, Depth+1);
2004 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2005 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2006 UndefElts2, Depth+1);
2007 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2008
2009 // If only the low elt is demanded and this is a scalarizable intrinsic,
2010 // scalarize it now.
2011 if (DemandedElts == 1) {
2012 switch (II->getIntrinsicID()) {
2013 default: break;
2014 case Intrinsic::x86_sse_sub_ss:
2015 case Intrinsic::x86_sse_mul_ss:
2016 case Intrinsic::x86_sse2_sub_sd:
2017 case Intrinsic::x86_sse2_mul_sd:
2018 // TODO: Lower MIN/MAX/ABS/etc
2019 Value *LHS = II->getOperand(1);
2020 Value *RHS = II->getOperand(2);
2021 // Extract the element as scalars.
2022 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2023 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2024
2025 switch (II->getIntrinsicID()) {
2026 default: assert(0 && "Case stmts out of sync!");
2027 case Intrinsic::x86_sse_sub_ss:
2028 case Intrinsic::x86_sse2_sub_sd:
2029 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
2030 II->getName()), *II);
2031 break;
2032 case Intrinsic::x86_sse_mul_ss:
2033 case Intrinsic::x86_sse2_mul_sd:
2034 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
2035 II->getName()), *II);
2036 break;
2037 }
2038
2039 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002040 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2041 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002042 InsertNewInstBefore(New, *II);
2043 AddSoonDeadInstToWorklist(*II, 0);
2044 return New;
2045 }
2046 }
2047
2048 // Output elements are undefined if both are undefined. Consider things
2049 // like undef&0. The result is known zero, not undef.
2050 UndefElts &= UndefElts2;
2051 break;
2052 }
2053 break;
2054 }
2055 }
2056 return MadeChange ? I : 0;
2057}
2058
Nick Lewycky455e1762007-09-06 02:40:25 +00002059/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00002060/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00002061/// @brief Determine if the icmp Predicate is true when both operands are equal
2062static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002063 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
2064 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2065 pred == ICmpInst::ICMP_SLE;
2066}
2067
Nick Lewycky455e1762007-09-06 02:40:25 +00002068/// @returns true if the specified compare instruction is
2069/// true when both operands are equal...
2070/// @brief Determine if the ICmpInst returns true when both operands are equal
2071static bool isTrueWhenEqual(ICmpInst &ICI) {
2072 return isTrueWhenEqual(ICI.getPredicate());
2073}
2074
Chris Lattner564a7272003-08-13 19:01:45 +00002075/// AssociativeOpt - Perform an optimization on an associative operator. This
2076/// function is designed to check a chain of associative operators for a
2077/// potential to apply a certain optimization. Since the optimization may be
2078/// applicable if the expression was reassociated, this checks the chain, then
2079/// reassociates the expression as necessary to expose the optimization
2080/// opportunity. This makes use of a special Functor, which must define
2081/// 'shouldApply' and 'apply' methods.
2082///
2083template<typename Functor>
2084Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2085 unsigned Opcode = Root.getOpcode();
2086 Value *LHS = Root.getOperand(0);
2087
2088 // Quick check, see if the immediate LHS matches...
2089 if (F.shouldApply(LHS))
2090 return F.apply(Root);
2091
2092 // Otherwise, if the LHS is not of the same opcode as the root, return.
2093 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002094 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002095 // Should we apply this transform to the RHS?
2096 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2097
2098 // If not to the RHS, check to see if we should apply to the LHS...
2099 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2100 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2101 ShouldApply = true;
2102 }
2103
2104 // If the functor wants to apply the optimization to the RHS of LHSI,
2105 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2106 if (ShouldApply) {
2107 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002108
Chris Lattner564a7272003-08-13 19:01:45 +00002109 // Now all of the instructions are in the current basic block, go ahead
2110 // and perform the reassociation.
2111 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2112
2113 // First move the selected RHS to the LHS of the root...
2114 Root.setOperand(0, LHSI->getOperand(1));
2115
2116 // Make what used to be the LHS of the root be the user of the root...
2117 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002118 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002119 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2120 return 0;
2121 }
Chris Lattner65725312004-04-16 18:08:07 +00002122 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002123 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002124 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2125 BasicBlock::iterator ARI = &Root; ++ARI;
2126 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2127 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002128
2129 // Now propagate the ExtraOperand down the chain of instructions until we
2130 // get to LHSI.
2131 while (TmpLHSI != LHSI) {
2132 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002133 // Move the instruction to immediately before the chain we are
2134 // constructing to avoid breaking dominance properties.
2135 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2136 BB->getInstList().insert(ARI, NextLHSI);
2137 ARI = NextLHSI;
2138
Chris Lattner564a7272003-08-13 19:01:45 +00002139 Value *NextOp = NextLHSI->getOperand(1);
2140 NextLHSI->setOperand(1, ExtraOperand);
2141 TmpLHSI = NextLHSI;
2142 ExtraOperand = NextOp;
2143 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002144
Chris Lattner564a7272003-08-13 19:01:45 +00002145 // Now that the instructions are reassociated, have the functor perform
2146 // the transformation...
2147 return F.apply(Root);
2148 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002149
Chris Lattner564a7272003-08-13 19:01:45 +00002150 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2151 }
2152 return 0;
2153}
2154
Dan Gohman844731a2008-05-13 00:00:25 +00002155namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002156
2157// AddRHS - Implements: X + X --> X << 1
2158struct AddRHS {
2159 Value *RHS;
2160 AddRHS(Value *rhs) : RHS(rhs) {}
2161 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2162 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00002163 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00002164 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002165 }
2166};
2167
2168// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2169// iff C1&C2 == 0
2170struct AddMaskingAnd {
2171 Constant *C2;
2172 AddMaskingAnd(Constant *c) : C2(c) {}
2173 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002174 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002175 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002176 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002177 }
2178 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00002179 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002180 }
2181};
2182
Dan Gohman844731a2008-05-13 00:00:25 +00002183}
2184
Chris Lattner6e7ba452005-01-01 16:22:27 +00002185static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002186 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002187 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002188 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002189 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002190
Reid Spencer3da59db2006-11-27 01:05:10 +00002191 return IC->InsertNewInstBefore(CastInst::create(
2192 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002193 }
2194
Chris Lattner2eefe512004-04-09 19:05:30 +00002195 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002196 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2197 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002198
Chris Lattner2eefe512004-04-09 19:05:30 +00002199 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2200 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002201 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2202 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002203 }
2204
2205 Value *Op0 = SO, *Op1 = ConstOperand;
2206 if (!ConstIsRHS)
2207 std::swap(Op0, Op1);
2208 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002209 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2210 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002211 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2212 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
2213 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002214 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002215 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002216 abort();
2217 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002218 return IC->InsertNewInstBefore(New, I);
2219}
2220
2221// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2222// constant as the other operand, try to fold the binary operator into the
2223// select arguments. This also works for Cast instructions, which obviously do
2224// not have a second operand.
2225static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2226 InstCombiner *IC) {
2227 // Don't modify shared select instructions
2228 if (!SI->hasOneUse()) return 0;
2229 Value *TV = SI->getOperand(1);
2230 Value *FV = SI->getOperand(2);
2231
2232 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002233 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002234 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002235
Chris Lattner6e7ba452005-01-01 16:22:27 +00002236 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2237 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2238
Gabor Greif051a9502008-04-06 20:25:17 +00002239 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2240 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002241 }
2242 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002243}
2244
Chris Lattner4e998b22004-09-29 05:07:12 +00002245
2246/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2247/// node as operand #0, see if we can fold the instruction into the PHI (which
2248/// is only possible if all operands to the PHI are constants).
2249Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2250 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002251 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002252 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002253
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002254 // Check to see if all of the operands of the PHI are constants. If there is
2255 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002256 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002257 BasicBlock *NonConstBB = 0;
2258 for (unsigned i = 0; i != NumPHIValues; ++i)
2259 if (!isa<Constant>(PN->getIncomingValue(i))) {
2260 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002261 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002262 NonConstBB = PN->getIncomingBlock(i);
2263
2264 // If the incoming non-constant value is in I's block, we have an infinite
2265 // loop.
2266 if (NonConstBB == I.getParent())
2267 return 0;
2268 }
2269
2270 // If there is exactly one non-constant value, we can insert a copy of the
2271 // operation in that block. However, if this is a critical edge, we would be
2272 // inserting the computation one some other paths (e.g. inside a loop). Only
2273 // do this if the pred block is unconditionally branching into the phi block.
2274 if (NonConstBB) {
2275 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2276 if (!BI || !BI->isUnconditional()) return 0;
2277 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002278
2279 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002280 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002281 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002282 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002283 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002284
2285 // Next, add all of the operands to the PHI.
2286 if (I.getNumOperands() == 2) {
2287 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002288 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002289 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002290 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002291 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2292 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2293 else
2294 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002295 } else {
2296 assert(PN->getIncomingBlock(i) == NonConstBB);
2297 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2298 InV = BinaryOperator::create(BO->getOpcode(),
2299 PN->getIncomingValue(i), C, "phitmp",
2300 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002301 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2302 InV = CmpInst::create(CI->getOpcode(),
2303 CI->getPredicate(),
2304 PN->getIncomingValue(i), C, "phitmp",
2305 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002306 else
2307 assert(0 && "Unknown binop!");
2308
Chris Lattnerdbab3862007-03-02 21:28:56 +00002309 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002310 }
2311 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002312 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002313 } else {
2314 CastInst *CI = cast<CastInst>(&I);
2315 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002316 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002317 Value *InV;
2318 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002319 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002320 } else {
2321 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00002322 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2323 I.getType(), "phitmp",
2324 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002325 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002326 }
2327 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002328 }
2329 }
2330 return ReplaceInstUsesWith(I, NewPN);
2331}
2332
Chris Lattner2454a2e2008-01-29 06:52:45 +00002333
2334/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2335/// value is never equal to -0.0.
2336///
2337/// Note that this function will need to be revisited when we support nondefault
2338/// rounding modes!
2339///
2340static bool CannotBeNegativeZero(const Value *V) {
2341 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2342 return !CFP->getValueAPF().isNegZero();
2343
2344 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2345 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2346 if (I->getOpcode() == Instruction::Add &&
2347 isa<ConstantFP>(I->getOperand(1)) &&
2348 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2349 return true;
2350
2351 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2352 if (II->getIntrinsicID() == Intrinsic::sqrt)
2353 return CannotBeNegativeZero(II->getOperand(1));
2354
2355 if (const CallInst *CI = dyn_cast<CallInst>(I))
2356 if (const Function *F = CI->getCalledFunction()) {
2357 if (F->isDeclaration()) {
2358 switch (F->getNameLen()) {
2359 case 3: // abs(x) != -0.0
2360 if (!strcmp(F->getNameStart(), "abs")) return true;
2361 break;
2362 case 4: // abs[lf](x) != -0.0
2363 if (!strcmp(F->getNameStart(), "absf")) return true;
2364 if (!strcmp(F->getNameStart(), "absl")) return true;
2365 break;
2366 }
2367 }
2368 }
2369 }
2370
2371 return false;
2372}
2373
2374
Chris Lattner7e708292002-06-25 16:13:24 +00002375Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002376 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002377 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002378
Chris Lattner66331a42004-04-10 22:01:55 +00002379 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002380 // X + undef -> undef
2381 if (isa<UndefValue>(RHS))
2382 return ReplaceInstUsesWith(I, RHS);
2383
Chris Lattner66331a42004-04-10 22:01:55 +00002384 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002385 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002386 if (RHSC->isNullValue())
2387 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002388 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002389 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2390 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002391 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002392 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002393
Chris Lattner66331a42004-04-10 22:01:55 +00002394 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002395 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002396 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002397 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002398 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00002399 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002400
2401 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2402 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002403 if (!isa<VectorType>(I.getType())) {
2404 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2405 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2406 KnownZero, KnownOne))
2407 return &I;
2408 }
Chris Lattner66331a42004-04-10 22:01:55 +00002409 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002410
2411 if (isa<PHINode>(LHS))
2412 if (Instruction *NV = FoldOpIntoPhi(I))
2413 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002414
Chris Lattner4f637d42006-01-06 17:59:59 +00002415 ConstantInt *XorRHS = 0;
2416 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002417 if (isa<ConstantInt>(RHSC) &&
2418 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002419 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002420 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002421
Zhou Sheng4351c642007-04-02 08:20:41 +00002422 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002423 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2424 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002425 do {
2426 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002427 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2428 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002429 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2430 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002431 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002432 if (!MaskedValueIsZero(XorLHS,
2433 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002434 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002435 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002436 }
2437 }
2438 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002439 C0080Val = APIntOps::lshr(C0080Val, Size);
2440 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2441 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002442
Reid Spencer35c38852007-03-28 01:36:16 +00002443 // FIXME: This shouldn't be necessary. When the backends can handle types
2444 // with funny bit widths then this whole cascade of if statements should
2445 // be removed. It is just here to get the size of the "middle" type back
2446 // up to something that the back ends can handle.
2447 const Type *MiddleType = 0;
2448 switch (Size) {
2449 default: break;
2450 case 32: MiddleType = Type::Int32Ty; break;
2451 case 16: MiddleType = Type::Int16Ty; break;
2452 case 8: MiddleType = Type::Int8Ty; break;
2453 }
2454 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002455 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002456 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002457 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002458 }
2459 }
Chris Lattner66331a42004-04-10 22:01:55 +00002460 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002461
Chris Lattner564a7272003-08-13 19:01:45 +00002462 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002463 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002464 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002465
2466 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2467 if (RHSI->getOpcode() == Instruction::Sub)
2468 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2469 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2470 }
2471 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2472 if (LHSI->getOpcode() == Instruction::Sub)
2473 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2474 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2475 }
Robert Bocchino71698282004-07-27 21:02:21 +00002476 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002477
Chris Lattner5c4afb92002-05-08 22:46:53 +00002478 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002479 // -A + -B --> -(A + B)
2480 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002481 if (LHS->getType()->isIntOrIntVector()) {
2482 if (Value *RHSV = dyn_castNegVal(RHS)) {
2483 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2484 InsertNewInstBefore(NewAdd, I);
2485 return BinaryOperator::createNeg(NewAdd);
2486 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002487 }
2488
2489 return BinaryOperator::createSub(RHS, LHSV);
2490 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002491
2492 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002493 if (!isa<Constant>(RHS))
2494 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002495 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002496
Misha Brukmanfd939082005-04-21 23:48:37 +00002497
Chris Lattner50af16a2004-11-13 19:50:12 +00002498 ConstantInt *C2;
2499 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2500 if (X == RHS) // X*C + X --> X * (C+1)
2501 return BinaryOperator::createMul(RHS, AddOne(C2));
2502
2503 // X*C1 + X*C2 --> X * (C1+C2)
2504 ConstantInt *C1;
2505 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002506 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002507 }
2508
2509 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002510 if (dyn_castFoldableMul(RHS, C2) == LHS)
2511 return BinaryOperator::createMul(LHS, AddOne(C2));
2512
Chris Lattnere617c9e2007-01-05 02:17:46 +00002513 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002514 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2515 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002516
Chris Lattnerad3448c2003-02-18 19:57:07 +00002517
Chris Lattner564a7272003-08-13 19:01:45 +00002518 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002519 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002520 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2521 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002522
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002523 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002524 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002525 Value *W, *X, *Y, *Z;
2526 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2527 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2528 if (W != Y) {
2529 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002530 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002531 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002532 std::swap(W, X);
2533 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002534 std::swap(Y, Z);
2535 std::swap(W, X);
2536 }
2537 }
2538
2539 if (W == Y) {
2540 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2541 LHS->getName()), I);
2542 return BinaryOperator::createMul(W, NewAdd);
2543 }
2544 }
2545 }
2546
Chris Lattner6b032052003-10-02 15:11:26 +00002547 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002548 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002549 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2550 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002551
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002552 // (X & FF00) + xx00 -> (X+xx00) & FF00
2553 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002554 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002555 if (Anded == CRHS) {
2556 // See if all bits from the first bit set in the Add RHS up are included
2557 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002558 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002559
2560 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002561 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002562
2563 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002564 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002565
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002566 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2567 // Okay, the xform is safe. Insert the new add pronto.
2568 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2569 LHS->getName()), I);
2570 return BinaryOperator::createAnd(NewAdd, C2);
2571 }
2572 }
2573 }
2574
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002575 // Try to fold constant add into select arguments.
2576 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002577 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002578 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002579 }
2580
Reid Spencer1628cec2006-10-26 06:15:43 +00002581 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002582 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002583 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002584 CastInst *CI = dyn_cast<CastInst>(LHS);
2585 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002586 if (!CI) {
2587 CI = dyn_cast<CastInst>(RHS);
2588 Other = LHS;
2589 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002590 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002591 (CI->getType()->getPrimitiveSizeInBits() ==
2592 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002593 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002594 unsigned AS =
2595 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002596 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2597 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002598 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002599 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002600 }
2601 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002602
Chris Lattner42790482007-12-20 01:56:58 +00002603 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002604 {
2605 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2606 Value *Other = RHS;
2607 if (!SI) {
2608 SI = dyn_cast<SelectInst>(RHS);
2609 Other = LHS;
2610 }
Chris Lattner42790482007-12-20 01:56:58 +00002611 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002612 Value *TV = SI->getTrueValue();
2613 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002614 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002615
2616 // Can we fold the add into the argument of the select?
2617 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002618 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2619 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002620 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002621 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2622 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002623 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002624 }
2625 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002626
2627 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2628 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2629 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2630 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002631
Chris Lattner7e708292002-06-25 16:13:24 +00002632 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002633}
2634
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002635// isSignBit - Return true if the value represented by the constant only has the
2636// highest order bit set.
2637static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002638 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002639 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002640}
2641
Chris Lattner7e708292002-06-25 16:13:24 +00002642Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002643 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002644
Chris Lattner233f7dc2002-08-12 21:17:25 +00002645 if (Op0 == Op1) // sub X, X -> 0
2646 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002647
Chris Lattner233f7dc2002-08-12 21:17:25 +00002648 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002649 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002650 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002651
Chris Lattnere87597f2004-10-16 18:11:37 +00002652 if (isa<UndefValue>(Op0))
2653 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2654 if (isa<UndefValue>(Op1))
2655 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2656
Chris Lattnerd65460f2003-11-05 01:06:05 +00002657 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2658 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002659 if (C->isAllOnesValue())
2660 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002661
Chris Lattnerd65460f2003-11-05 01:06:05 +00002662 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002663 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002664 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002665 return BinaryOperator::createAdd(X, AddOne(C));
2666
Chris Lattner76b7a062007-01-15 07:02:54 +00002667 // -(X >>u 31) -> (X >>s 31)
2668 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002669 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002670 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002671 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002672 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002673 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002674 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002675 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002676 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002677 return BinaryOperator::create(Instruction::AShr,
2678 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002679 }
2680 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002681 }
2682 else if (SI->getOpcode() == Instruction::AShr) {
2683 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2684 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002685 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002686 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002687 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002688 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002689 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002690 }
2691 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002692 }
2693 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002694 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002695
2696 // Try to fold constant sub into select arguments.
2697 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002698 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002699 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002700
2701 if (isa<PHINode>(Op0))
2702 if (Instruction *NV = FoldOpIntoPhi(I))
2703 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002704 }
2705
Chris Lattner43d84d62005-04-07 16:15:25 +00002706 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2707 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002708 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002709 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002710 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002711 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002712 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002713 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2714 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2715 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002716 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002717 Op1I->getOperand(0));
2718 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002719 }
2720
Chris Lattnerfd059242003-10-15 16:48:29 +00002721 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002722 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2723 // is not used by anyone else...
2724 //
Chris Lattner0517e722004-02-02 20:09:56 +00002725 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002726 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002727 // Swap the two operands of the subexpr...
2728 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2729 Op1I->setOperand(0, IIOp1);
2730 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002731
Chris Lattnera2881962003-02-18 19:28:33 +00002732 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002733 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002734 }
2735
2736 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2737 //
2738 if (Op1I->getOpcode() == Instruction::And &&
2739 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2740 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2741
Chris Lattnerf523d062004-06-09 05:08:07 +00002742 Value *NewNot =
2743 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002744 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002745 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002746
Reid Spencerac5209e2006-10-16 23:08:08 +00002747 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002748 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002749 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002750 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002751 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002752 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002753 ConstantExpr::getNeg(DivRHS));
2754
Chris Lattnerad3448c2003-02-18 19:57:07 +00002755 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002756 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002757 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002758 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002759 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002760 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002761
2762 // X - ((X / Y) * Y) --> X % Y
2763 if (Op1I->getOpcode() == Instruction::Mul)
2764 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2765 if (Op0 == I->getOperand(0) &&
2766 Op1I->getOperand(1) == I->getOperand(1)) {
2767 if (I->getOpcode() == Instruction::SDiv)
2768 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2769 if (I->getOpcode() == Instruction::UDiv)
2770 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2771 }
Chris Lattner40371712002-05-09 01:29:19 +00002772 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002773 }
Chris Lattnera2881962003-02-18 19:28:33 +00002774
Chris Lattner9919e3d2006-12-02 00:13:08 +00002775 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002776 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002777 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002778 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2779 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2780 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2781 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002782 } else if (Op0I->getOpcode() == Instruction::Sub) {
2783 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2784 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002785 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002786 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002787
Chris Lattner50af16a2004-11-13 19:50:12 +00002788 ConstantInt *C1;
2789 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002790 if (X == Op1) // X*C - X --> X * (C-1)
2791 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002792
Chris Lattner50af16a2004-11-13 19:50:12 +00002793 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2794 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Sheng58d13af2008-02-22 10:00:35 +00002795 return BinaryOperator::createMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002796 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002797 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002798}
2799
Chris Lattnera0141b92007-07-15 20:42:37 +00002800/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2801/// comparison only checks the sign bit. If it only checks the sign bit, set
2802/// TrueIfSigned if the result of the comparison is true when the input value is
2803/// signed.
2804static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2805 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002806 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002807 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2808 TrueIfSigned = true;
2809 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002810 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2811 TrueIfSigned = true;
2812 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002813 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2814 TrueIfSigned = false;
2815 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002816 case ICmpInst::ICMP_UGT:
2817 // True if LHS u> RHS and RHS == high-bit-mask - 1
2818 TrueIfSigned = true;
2819 return RHS->getValue() ==
2820 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2821 case ICmpInst::ICMP_UGE:
2822 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2823 TrueIfSigned = true;
2824 return RHS->getValue() ==
2825 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002826 default:
2827 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002828 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002829}
2830
Chris Lattner7e708292002-06-25 16:13:24 +00002831Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002832 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002833 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002834
Chris Lattnere87597f2004-10-16 18:11:37 +00002835 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2836 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2837
Chris Lattner233f7dc2002-08-12 21:17:25 +00002838 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002839 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2840 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002841
2842 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002843 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002844 if (SI->getOpcode() == Instruction::Shl)
2845 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002846 return BinaryOperator::createMul(SI->getOperand(0),
2847 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002848
Zhou Sheng843f07672007-04-19 05:39:12 +00002849 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002850 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2851 if (CI->equalsInt(1)) // X * 1 == X
2852 return ReplaceInstUsesWith(I, Op0);
2853 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002854 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002855
Zhou Sheng97b52c22007-03-29 01:57:21 +00002856 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002857 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002858 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002859 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002860 }
Robert Bocchino71698282004-07-27 21:02:21 +00002861 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002862 if (Op1F->isNullValue())
2863 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002864
Chris Lattnera2881962003-02-18 19:28:33 +00002865 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2866 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002867 // We need a better interface for long double here.
2868 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2869 if (Op1F->isExactlyValue(1.0))
2870 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002871 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002872
2873 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2874 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2875 isa<ConstantInt>(Op0I->getOperand(1))) {
2876 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2877 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2878 Op1, "tmp");
2879 InsertNewInstBefore(Add, I);
2880 Value *C1C2 = ConstantExpr::getMul(Op1,
2881 cast<Constant>(Op0I->getOperand(1)));
2882 return BinaryOperator::createAdd(Add, C1C2);
2883
2884 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002885
2886 // Try to fold constant mul into select arguments.
2887 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002888 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002889 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002890
2891 if (isa<PHINode>(Op0))
2892 if (Instruction *NV = FoldOpIntoPhi(I))
2893 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002894 }
2895
Chris Lattnera4f445b2003-03-10 23:23:04 +00002896 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2897 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002898 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002899
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002900 // If one of the operands of the multiply is a cast from a boolean value, then
2901 // we know the bool is either zero or one, so this is a 'masking' multiply.
2902 // See if we can simplify things based on how the boolean was originally
2903 // formed.
2904 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002905 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002906 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002907 BoolCast = CI;
2908 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002909 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002910 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002911 BoolCast = CI;
2912 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002913 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002914 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2915 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002916 bool TIS = false;
2917
Reid Spencere4d87aa2006-12-23 06:05:41 +00002918 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002919 // multiply into a shift/and combination.
2920 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002921 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2922 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002923 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002924 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002925 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002926 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002927 InsertNewInstBefore(
2928 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002929 BoolCast->getOperand(0)->getName()+
2930 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002931
2932 // If the multiply type is not the same as the source type, sign extend
2933 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002934 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002935 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2936 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002937 Instruction::CastOps opcode =
2938 (SrcBits == DstBits ? Instruction::BitCast :
2939 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2940 V = InsertCastBefore(opcode, V, I.getType(), I);
2941 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002942
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002943 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002944 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002945 }
2946 }
2947 }
2948
Chris Lattner7e708292002-06-25 16:13:24 +00002949 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002950}
2951
Reid Spencer1628cec2006-10-26 06:15:43 +00002952/// This function implements the transforms on div instructions that work
2953/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2954/// used by the visitors to those instructions.
2955/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002956Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002957 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002958
Chris Lattner50b2ca42008-02-19 06:12:18 +00002959 // undef / X -> 0 for integer.
2960 // undef / X -> undef for FP (the undef could be a snan).
2961 if (isa<UndefValue>(Op0)) {
2962 if (Op0->getType()->isFPOrFPVector())
2963 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002964 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002965 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002966
2967 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002968 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002969 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002970
Chris Lattner25feae52008-01-28 00:58:18 +00002971 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2972 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002973 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002974 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2975 // the same basic block, then we replace the select with Y, and the
2976 // condition of the select with false (if the cond value is in the same BB).
2977 // If the select has uses other than the div, this allows them to be
2978 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2979 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002980 if (ST->isNullValue()) {
2981 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2982 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002983 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002984 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2985 I.setOperand(1, SI->getOperand(2));
2986 else
2987 UpdateValueUsesWith(SI, SI->getOperand(2));
2988 return &I;
2989 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002990
Chris Lattner25feae52008-01-28 00:58:18 +00002991 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2992 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002993 if (ST->isNullValue()) {
2994 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2995 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002996 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002997 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2998 I.setOperand(1, SI->getOperand(1));
2999 else
3000 UpdateValueUsesWith(SI, SI->getOperand(1));
3001 return &I;
3002 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003003 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003004
Reid Spencer1628cec2006-10-26 06:15:43 +00003005 return 0;
3006}
Misha Brukmanfd939082005-04-21 23:48:37 +00003007
Reid Spencer1628cec2006-10-26 06:15:43 +00003008/// This function implements the transforms common to both integer division
3009/// instructions (udiv and sdiv). It is called by the visitors to those integer
3010/// division instructions.
3011/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003012Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3014
3015 if (Instruction *Common = commonDivTransforms(I))
3016 return Common;
3017
3018 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3019 // div X, 1 == X
3020 if (RHS->equalsInt(1))
3021 return ReplaceInstUsesWith(I, Op0);
3022
3023 // (X / C1) / C2 -> X / (C1*C2)
3024 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3025 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3026 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003027 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3028 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3029 else
3030 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
3031 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003032 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003033
Reid Spencerbca0e382007-03-23 20:05:17 +00003034 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003035 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3036 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3037 return R;
3038 if (isa<PHINode>(Op0))
3039 if (Instruction *NV = FoldOpIntoPhi(I))
3040 return NV;
3041 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003042 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003043
Chris Lattnera2881962003-02-18 19:28:33 +00003044 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003045 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003046 if (LHS->equalsInt(0))
3047 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3048
Reid Spencer1628cec2006-10-26 06:15:43 +00003049 return 0;
3050}
3051
3052Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3053 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3054
3055 // Handle the integer div common cases
3056 if (Instruction *Common = commonIDivTransforms(I))
3057 return Common;
3058
3059 // X udiv C^2 -> X >> C
3060 // Check to see if this is an unsigned division with an exact power of 2,
3061 // if so, convert to a right shift.
3062 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003063 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00003064 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003065 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003066 }
3067
3068 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003069 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003070 if (RHSI->getOpcode() == Instruction::Shl &&
3071 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003072 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003073 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003074 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003075 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003076 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003077 Constant *C2V = ConstantInt::get(NTy, C2);
3078 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003079 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00003080 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003081 }
3082 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003083 }
3084
Reid Spencer1628cec2006-10-26 06:15:43 +00003085 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3086 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003087 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003088 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003089 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003090 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003091 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003092 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003093 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003094 // Construct the "on true" case of the select
3095 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3096 Instruction *TSI = BinaryOperator::createLShr(
3097 Op0, TC, SI->getName()+".t");
3098 TSI = InsertNewInstBefore(TSI, I);
3099
3100 // Construct the "on false" case of the select
3101 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3102 Instruction *FSI = BinaryOperator::createLShr(
3103 Op0, FC, SI->getName()+".f");
3104 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003105
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003106 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003107 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003108 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003109 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003110 return 0;
3111}
3112
Reid Spencer1628cec2006-10-26 06:15:43 +00003113Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3114 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3115
3116 // Handle the integer div common cases
3117 if (Instruction *Common = commonIDivTransforms(I))
3118 return Common;
3119
3120 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3121 // sdiv X, -1 == -X
3122 if (RHS->isAllOnesValue())
3123 return BinaryOperator::createNeg(Op0);
3124
3125 // -X/C -> X/-C
3126 if (Value *LHSNeg = dyn_castNegVal(Op0))
3127 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3128 }
3129
3130 // If the sign bits of both operands are zero (i.e. we can prove they are
3131 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003132 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003133 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003134 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003135 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00003136 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3137 }
3138 }
3139
3140 return 0;
3141}
3142
3143Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3144 return commonDivTransforms(I);
3145}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003146
Reid Spencer0a783f72006-11-02 01:53:59 +00003147/// This function implements the transforms on rem instructions that work
3148/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3149/// is used by the visitors to those instructions.
3150/// @brief Transforms common to all three rem instructions
3151Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003152 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003153
Chris Lattner50b2ca42008-02-19 06:12:18 +00003154 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003155 if (Constant *LHS = dyn_cast<Constant>(Op0))
3156 if (LHS->isNullValue())
3157 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3158
Chris Lattner50b2ca42008-02-19 06:12:18 +00003159 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3160 if (I.getType()->isFPOrFPVector())
3161 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003162 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003163 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003164 if (isa<UndefValue>(Op1))
3165 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003166
3167 // Handle cases involving: rem X, (select Cond, Y, Z)
3168 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3169 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3170 // the same basic block, then we replace the select with Y, and the
3171 // condition of the select with false (if the cond value is in the same
3172 // BB). If the select has uses other than the div, this allows them to be
3173 // simplified also.
3174 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3175 if (ST->isNullValue()) {
3176 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3177 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003178 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003179 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3180 I.setOperand(1, SI->getOperand(2));
3181 else
3182 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003183 return &I;
3184 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003185 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3186 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3187 if (ST->isNullValue()) {
3188 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3189 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003190 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003191 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3192 I.setOperand(1, SI->getOperand(1));
3193 else
3194 UpdateValueUsesWith(SI, SI->getOperand(1));
3195 return &I;
3196 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003197 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003198
Reid Spencer0a783f72006-11-02 01:53:59 +00003199 return 0;
3200}
3201
3202/// This function implements the transforms common to both integer remainder
3203/// instructions (urem and srem). It is called by the visitors to those integer
3204/// remainder instructions.
3205/// @brief Common integer remainder transforms
3206Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3207 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3208
3209 if (Instruction *common = commonRemTransforms(I))
3210 return common;
3211
Chris Lattner857e8cd2004-12-12 21:48:58 +00003212 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003213 // X % 0 == undef, we don't need to preserve faults!
3214 if (RHS->equalsInt(0))
3215 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3216
Chris Lattnera2881962003-02-18 19:28:33 +00003217 if (RHS->equalsInt(1)) // X % 1 == 0
3218 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3219
Chris Lattner97943922006-02-28 05:49:21 +00003220 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3221 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3222 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3223 return R;
3224 } else if (isa<PHINode>(Op0I)) {
3225 if (Instruction *NV = FoldOpIntoPhi(I))
3226 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003227 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003228
3229 // See if we can fold away this rem instruction.
3230 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3231 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3232 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3233 KnownZero, KnownOne))
3234 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003235 }
Chris Lattnera2881962003-02-18 19:28:33 +00003236 }
3237
Reid Spencer0a783f72006-11-02 01:53:59 +00003238 return 0;
3239}
3240
3241Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3242 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3243
3244 if (Instruction *common = commonIRemTransforms(I))
3245 return common;
3246
3247 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3248 // X urem C^2 -> X and C
3249 // Check to see if this is an unsigned remainder with an exact power of 2,
3250 // if so, convert to a bitwise and.
3251 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003252 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00003253 return BinaryOperator::createAnd(Op0, SubOne(C));
3254 }
3255
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003256 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003257 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3258 if (RHSI->getOpcode() == Instruction::Shl &&
3259 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003260 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003261 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3262 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3263 "tmp"), I);
3264 return BinaryOperator::createAnd(Op0, Add);
3265 }
3266 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003267 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003268
Reid Spencer0a783f72006-11-02 01:53:59 +00003269 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3270 // where C1&C2 are powers of two.
3271 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3272 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3273 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3274 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003275 if ((STO->getValue().isPowerOf2()) &&
3276 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003277 Value *TrueAnd = InsertNewInstBefore(
3278 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3279 Value *FalseAnd = InsertNewInstBefore(
3280 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003281 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003282 }
3283 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003284 }
3285
Chris Lattner3f5b8772002-05-06 16:14:14 +00003286 return 0;
3287}
3288
Reid Spencer0a783f72006-11-02 01:53:59 +00003289Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3290 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3291
Dan Gohmancff55092007-11-05 23:16:33 +00003292 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003293 if (Instruction *common = commonIRemTransforms(I))
3294 return common;
3295
3296 if (Value *RHSNeg = dyn_castNegVal(Op1))
3297 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003298 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003299 // X % -Y -> X % Y
3300 AddUsesToWorkList(I);
3301 I.setOperand(1, RHSNeg);
3302 return &I;
3303 }
3304
Dan Gohmancff55092007-11-05 23:16:33 +00003305 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003306 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003307 if (I.getType()->isInteger()) {
3308 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3309 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3310 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3311 return BinaryOperator::createURem(Op0, Op1, I.getName());
3312 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003313 }
3314
3315 return 0;
3316}
3317
3318Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003319 return commonRemTransforms(I);
3320}
3321
Chris Lattner8b170942002-08-09 23:47:40 +00003322// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003323static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003324 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003325 if (!isSigned)
3326 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3327 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003328}
3329
3330// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003331static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003332 if (!isSigned)
3333 return C->getValue() == 1; // unsigned
3334
3335 // Calculate 1111111111000000000000
3336 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3337 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003338}
3339
Chris Lattner457dd822004-06-09 07:59:58 +00003340// isOneBitSet - Return true if there is exactly one bit set in the specified
3341// constant.
3342static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003343 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003344}
3345
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003346// isHighOnes - Return true if the constant is of the form 1+0+.
3347// This is the same as lowones(~X).
3348static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003349 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003350}
3351
Reid Spencere4d87aa2006-12-23 06:05:41 +00003352/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003353/// are carefully arranged to allow folding of expressions such as:
3354///
3355/// (A < B) | (A > B) --> (A != B)
3356///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003357/// Note that this is only valid if the first and second predicates have the
3358/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003359///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003360/// Three bits are used to represent the condition, as follows:
3361/// 0 A > B
3362/// 1 A == B
3363/// 2 A < B
3364///
3365/// <=> Value Definition
3366/// 000 0 Always false
3367/// 001 1 A > B
3368/// 010 2 A == B
3369/// 011 3 A >= B
3370/// 100 4 A < B
3371/// 101 5 A != B
3372/// 110 6 A <= B
3373/// 111 7 Always true
3374///
3375static unsigned getICmpCode(const ICmpInst *ICI) {
3376 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003377 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003378 case ICmpInst::ICMP_UGT: return 1; // 001
3379 case ICmpInst::ICMP_SGT: return 1; // 001
3380 case ICmpInst::ICMP_EQ: return 2; // 010
3381 case ICmpInst::ICMP_UGE: return 3; // 011
3382 case ICmpInst::ICMP_SGE: return 3; // 011
3383 case ICmpInst::ICMP_ULT: return 4; // 100
3384 case ICmpInst::ICMP_SLT: return 4; // 100
3385 case ICmpInst::ICMP_NE: return 5; // 101
3386 case ICmpInst::ICMP_ULE: return 6; // 110
3387 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003388 // True -> 7
3389 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003390 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003391 return 0;
3392 }
3393}
3394
Reid Spencere4d87aa2006-12-23 06:05:41 +00003395/// getICmpValue - This is the complement of getICmpCode, which turns an
3396/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003397/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003398/// of predicate to use in new icmp instructions.
3399static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3400 switch (code) {
3401 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003402 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003403 case 1:
3404 if (sign)
3405 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3406 else
3407 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3408 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3409 case 3:
3410 if (sign)
3411 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3412 else
3413 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3414 case 4:
3415 if (sign)
3416 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3417 else
3418 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3419 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3420 case 6:
3421 if (sign)
3422 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3423 else
3424 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003425 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003426 }
3427}
3428
Reid Spencere4d87aa2006-12-23 06:05:41 +00003429static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3430 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3431 (ICmpInst::isSignedPredicate(p1) &&
3432 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3433 (ICmpInst::isSignedPredicate(p2) &&
3434 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3435}
3436
3437namespace {
3438// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3439struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003440 InstCombiner &IC;
3441 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003442 ICmpInst::Predicate pred;
3443 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3444 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3445 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003446 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003447 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3448 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003449 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3450 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003451 return false;
3452 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003453 Instruction *apply(Instruction &Log) const {
3454 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3455 if (ICI->getOperand(0) != LHS) {
3456 assert(ICI->getOperand(1) == LHS);
3457 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003458 }
3459
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003460 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003461 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003462 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003463 unsigned Code;
3464 switch (Log.getOpcode()) {
3465 case Instruction::And: Code = LHSCode & RHSCode; break;
3466 case Instruction::Or: Code = LHSCode | RHSCode; break;
3467 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003468 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003469 }
3470
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003471 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3472 ICmpInst::isSignedPredicate(ICI->getPredicate());
3473
3474 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003475 if (Instruction *I = dyn_cast<Instruction>(RV))
3476 return I;
3477 // Otherwise, it's a constant boolean value...
3478 return IC.ReplaceInstUsesWith(Log, RV);
3479 }
3480};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003481} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003482
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003483// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3484// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003485// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003486Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003487 ConstantInt *OpRHS,
3488 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003489 BinaryOperator &TheAnd) {
3490 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003491 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003492 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003493 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003494
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003495 switch (Op->getOpcode()) {
3496 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003497 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003498 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003499 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003500 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003501 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003502 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003503 }
3504 break;
3505 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003506 if (Together == AndRHS) // (X | C) & C --> C
3507 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003508
Chris Lattner6e7ba452005-01-01 16:22:27 +00003509 if (Op->hasOneUse() && Together != OpRHS) {
3510 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003511 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003512 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003513 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003514 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003515 }
3516 break;
3517 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003518 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003519 // Adding a one to a single bit bit-field should be turned into an XOR
3520 // of the bit. First thing to check is to see if this AND is with a
3521 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003522 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003523
3524 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003525 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003526 // Ok, at this point, we know that we are masking the result of the
3527 // ADD down to exactly one bit. If the constant we are adding has
3528 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003529 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003530
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003531 // Check to see if any bits below the one bit set in AndRHSV are set.
3532 if ((AddRHS & (AndRHSV-1)) == 0) {
3533 // If not, the only thing that can effect the output of the AND is
3534 // the bit specified by AndRHSV. If that bit is set, the effect of
3535 // the XOR is to toggle the bit. If it is clear, then the ADD has
3536 // no effect.
3537 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3538 TheAnd.setOperand(0, X);
3539 return &TheAnd;
3540 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003541 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003542 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003543 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003544 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003545 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 }
3547 }
3548 }
3549 }
3550 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003551
3552 case Instruction::Shl: {
3553 // We know that the AND will not produce any of the bits shifted in, so if
3554 // the anded constant includes them, clear them now!
3555 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003556 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003557 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003558 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3559 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003560
Zhou Sheng290bec52007-03-29 08:15:12 +00003561 if (CI->getValue() == ShlMask) {
3562 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003563 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3564 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003565 TheAnd.setOperand(1, CI);
3566 return &TheAnd;
3567 }
3568 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003569 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003570 case Instruction::LShr:
3571 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003572 // We know that the AND will not produce any of the bits shifted in, so if
3573 // the anded constant includes them, clear them now! This only applies to
3574 // unsigned shifts, because a signed shr may bring in set bits!
3575 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003576 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003577 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003578 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3579 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003580
Zhou Sheng290bec52007-03-29 08:15:12 +00003581 if (CI->getValue() == ShrMask) {
3582 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003583 return ReplaceInstUsesWith(TheAnd, Op);
3584 } else if (CI != AndRHS) {
3585 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3586 return &TheAnd;
3587 }
3588 break;
3589 }
3590 case Instruction::AShr:
3591 // Signed shr.
3592 // See if this is shifting in some sign extension, then masking it out
3593 // with an and.
3594 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003595 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003596 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003597 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3598 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003599 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003600 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003601 // Make the argument unsigned.
3602 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003603 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003604 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003605 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003606 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003607 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003608 }
3609 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003610 }
3611 return 0;
3612}
3613
Chris Lattner8b170942002-08-09 23:47:40 +00003614
Chris Lattnera96879a2004-09-29 17:40:11 +00003615/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3616/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003617/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3618/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003619/// insert new instructions.
3620Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003621 bool isSigned, bool Inside,
3622 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003623 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003624 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003625 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003626
Chris Lattnera96879a2004-09-29 17:40:11 +00003627 if (Inside) {
3628 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003629 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003630
Reid Spencere4d87aa2006-12-23 06:05:41 +00003631 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003632 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003633 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003634 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3635 return new ICmpInst(pred, V, Hi);
3636 }
3637
3638 // Emit V-Lo <u Hi-Lo
3639 Constant *NegLo = ConstantExpr::getNeg(Lo);
3640 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003641 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003642 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3643 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003644 }
3645
3646 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003647 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003648
Reid Spencere4e40032007-03-21 23:19:50 +00003649 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003650 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003651 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003652 ICmpInst::Predicate pred = (isSigned ?
3653 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3654 return new ICmpInst(pred, V, Hi);
3655 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003656
Reid Spencere4e40032007-03-21 23:19:50 +00003657 // Emit V-Lo >u Hi-1-Lo
3658 // Note that Hi has already had one subtracted from it, above.
3659 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003660 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003661 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003662 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3663 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003664}
3665
Chris Lattner7203e152005-09-18 07:22:02 +00003666// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3667// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3668// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3669// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003670static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003671 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003672 uint32_t BitWidth = Val->getType()->getBitWidth();
3673 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003674
3675 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003676 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003677 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003678 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003679 return true;
3680}
3681
Chris Lattner7203e152005-09-18 07:22:02 +00003682/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3683/// where isSub determines whether the operator is a sub. If we can fold one of
3684/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003685///
3686/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3687/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3688/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3689///
3690/// return (A +/- B).
3691///
3692Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003693 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003694 Instruction &I) {
3695 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3696 if (!LHSI || LHSI->getNumOperands() != 2 ||
3697 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3698
3699 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3700
3701 switch (LHSI->getOpcode()) {
3702 default: return 0;
3703 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003704 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003705 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003706 if ((Mask->getValue().countLeadingZeros() +
3707 Mask->getValue().countPopulation()) ==
3708 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003709 break;
3710
3711 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3712 // part, we don't need any explicit masks to take them out of A. If that
3713 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003714 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003715 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003716 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003717 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003718 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003719 break;
3720 }
3721 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003722 return 0;
3723 case Instruction::Or:
3724 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003725 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003726 if ((Mask->getValue().countLeadingZeros() +
3727 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003728 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003729 break;
3730 return 0;
3731 }
3732
3733 Instruction *New;
3734 if (isSub)
3735 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3736 else
3737 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3738 return InsertNewInstBefore(New, I);
3739}
3740
Chris Lattner7e708292002-06-25 16:13:24 +00003741Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003742 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003743 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003744
Chris Lattnere87597f2004-10-16 18:11:37 +00003745 if (isa<UndefValue>(Op1)) // X & undef -> 0
3746 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3747
Chris Lattner6e7ba452005-01-01 16:22:27 +00003748 // and X, X = X
3749 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003750 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003751
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003752 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003753 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003754 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003755 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3756 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3757 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003758 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003759 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003760 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003761 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003762 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003763 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003764 } else if (isa<ConstantAggregateZero>(Op1)) {
3765 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003766 }
3767 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003768
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003769 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003770 const APInt& AndRHSMask = AndRHS->getValue();
3771 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003772
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003773 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003774 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003775 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003776 Value *Op0LHS = Op0I->getOperand(0);
3777 Value *Op0RHS = Op0I->getOperand(1);
3778 switch (Op0I->getOpcode()) {
3779 case Instruction::Xor:
3780 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003781 // If the mask is only needed on one incoming arm, push it up.
3782 if (Op0I->hasOneUse()) {
3783 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3784 // Not masking anything out for the LHS, move to RHS.
3785 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3786 Op0RHS->getName()+".masked");
3787 InsertNewInstBefore(NewRHS, I);
3788 return BinaryOperator::create(
3789 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003790 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003791 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003792 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3793 // Not masking anything out for the RHS, move to LHS.
3794 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3795 Op0LHS->getName()+".masked");
3796 InsertNewInstBefore(NewLHS, I);
3797 return BinaryOperator::create(
3798 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3799 }
3800 }
3801
Chris Lattner6e7ba452005-01-01 16:22:27 +00003802 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003803 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003804 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3805 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3806 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3807 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3808 return BinaryOperator::createAnd(V, AndRHS);
3809 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3810 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003811 break;
3812
3813 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003814 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3815 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3816 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3817 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3818 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003819 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003820 }
3821
Chris Lattner58403262003-07-23 19:25:52 +00003822 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003823 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003824 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003825 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003826 // If this is an integer truncation or change from signed-to-unsigned, and
3827 // if the source is an and/or with immediate, transform it. This
3828 // frequently occurs for bitfield accesses.
3829 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003830 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003831 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003832 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003833 if (CastOp->getOpcode() == Instruction::And) {
3834 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003835 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3836 // This will fold the two constants together, which may allow
3837 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003838 Instruction *NewCast = CastInst::createTruncOrBitCast(
3839 CastOp->getOperand(0), I.getType(),
3840 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003841 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003842 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003843 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003844 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003845 return BinaryOperator::createAnd(NewCast, C3);
3846 } else if (CastOp->getOpcode() == Instruction::Or) {
3847 // Change: and (cast (or X, C1) to T), C2
3848 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003849 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003850 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3851 return ReplaceInstUsesWith(I, AndRHS);
3852 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003853 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003854 }
Chris Lattner06782f82003-07-23 19:36:21 +00003855 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003856
3857 // Try to fold constant and into select arguments.
3858 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003859 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003860 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003861 if (isa<PHINode>(Op0))
3862 if (Instruction *NV = FoldOpIntoPhi(I))
3863 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003864 }
3865
Chris Lattner8d969642003-03-10 23:06:50 +00003866 Value *Op0NotVal = dyn_castNotVal(Op0);
3867 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003868
Chris Lattner5b62aa72004-06-18 06:07:51 +00003869 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3870 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3871
Misha Brukmancb6267b2004-07-30 12:50:08 +00003872 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003873 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003874 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3875 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003876 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003877 return BinaryOperator::createNot(Or);
3878 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003879
3880 {
Chris Lattner003b6202007-06-15 05:58:24 +00003881 Value *A = 0, *B = 0, *C = 0, *D = 0;
3882 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003883 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3884 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003885
3886 // (A|B) & ~(A&B) -> A^B
3887 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3888 if ((A == C && B == D) || (A == D && B == C))
3889 return BinaryOperator::createXor(A, B);
3890 }
3891 }
3892
3893 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003894 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3895 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003896
3897 // ~(A&B) & (A|B) -> A^B
3898 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3899 if ((A == C && B == D) || (A == D && B == C))
3900 return BinaryOperator::createXor(A, B);
3901 }
3902 }
Chris Lattner64daab52006-04-01 08:03:55 +00003903
3904 if (Op0->hasOneUse() &&
3905 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3906 if (A == Op1) { // (A^B)&A -> A&(A^B)
3907 I.swapOperands(); // Simplify below
3908 std::swap(Op0, Op1);
3909 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3910 cast<BinaryOperator>(Op0)->swapOperands();
3911 I.swapOperands(); // Simplify below
3912 std::swap(Op0, Op1);
3913 }
3914 }
3915 if (Op1->hasOneUse() &&
3916 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3917 if (B == Op0) { // B&(A^B) -> B&(B^A)
3918 cast<BinaryOperator>(Op1)->swapOperands();
3919 std::swap(A, B);
3920 }
3921 if (A == Op0) { // A&(A^B) -> A & ~B
3922 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3923 InsertNewInstBefore(NotB, I);
3924 return BinaryOperator::createAnd(A, NotB);
3925 }
3926 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003927 }
3928
Reid Spencere4d87aa2006-12-23 06:05:41 +00003929 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3930 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3931 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003932 return R;
3933
Chris Lattner955f3312004-09-28 21:48:02 +00003934 Value *LHSVal, *RHSVal;
3935 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003936 ICmpInst::Predicate LHSCC, RHSCC;
3937 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3938 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3939 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3940 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3941 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3942 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3943 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003944 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3945
3946 // Don't try to fold ICMP_SLT + ICMP_ULT.
3947 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3948 ICmpInst::isSignedPredicate(LHSCC) ==
3949 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003950 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003951 ICmpInst::Predicate GT;
3952 if (ICmpInst::isSignedPredicate(LHSCC) ||
3953 (ICmpInst::isEquality(LHSCC) &&
3954 ICmpInst::isSignedPredicate(RHSCC)))
3955 GT = ICmpInst::ICMP_SGT;
3956 else
3957 GT = ICmpInst::ICMP_UGT;
3958
Reid Spencere4d87aa2006-12-23 06:05:41 +00003959 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3960 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003961 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003962 std::swap(LHS, RHS);
3963 std::swap(LHSCst, RHSCst);
3964 std::swap(LHSCC, RHSCC);
3965 }
3966
Reid Spencere4d87aa2006-12-23 06:05:41 +00003967 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003968 // comparing a value against two constants and and'ing the result
3969 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003970 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3971 // (from the FoldICmpLogical check above), that the two constants
3972 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003973 assert(LHSCst != RHSCst && "Compares not folded above?");
3974
3975 switch (LHSCC) {
3976 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003977 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003978 switch (RHSCC) {
3979 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003980 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3981 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3982 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003983 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003984 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3985 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3986 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003987 return ReplaceInstUsesWith(I, LHS);
3988 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003989 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003990 switch (RHSCC) {
3991 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003992 case ICmpInst::ICMP_ULT:
3993 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3994 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3995 break; // (X != 13 & X u< 15) -> no change
3996 case ICmpInst::ICMP_SLT:
3997 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3998 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3999 break; // (X != 13 & X s< 15) -> no change
4000 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4001 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4002 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004003 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004004 case ICmpInst::ICMP_NE:
4005 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004006 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4007 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4008 LHSVal->getName()+".off");
4009 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004010 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4011 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004012 }
4013 break; // (X != 13 & X != 15) -> no change
4014 }
4015 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004016 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004017 switch (RHSCC) {
4018 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004019 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4020 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004021 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004022 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4023 break;
4024 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4025 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004026 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004027 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4028 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004029 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004030 break;
4031 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004032 switch (RHSCC) {
4033 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004034 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4035 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004036 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004037 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4038 break;
4039 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4040 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004041 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004042 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4043 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004044 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004045 break;
4046 case ICmpInst::ICMP_UGT:
4047 switch (RHSCC) {
4048 default: assert(0 && "Unknown integer condition code!");
4049 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4050 return ReplaceInstUsesWith(I, LHS);
4051 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4052 return ReplaceInstUsesWith(I, RHS);
4053 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4054 break;
4055 case ICmpInst::ICMP_NE:
4056 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4057 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4058 break; // (X u> 13 & X != 15) -> no change
4059 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4060 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4061 true, I);
4062 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4063 break;
4064 }
4065 break;
4066 case ICmpInst::ICMP_SGT:
4067 switch (RHSCC) {
4068 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004069 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004070 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4071 return ReplaceInstUsesWith(I, RHS);
4072 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4073 break;
4074 case ICmpInst::ICMP_NE:
4075 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4076 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4077 break; // (X s> 13 & X != 15) -> no change
4078 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4079 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4080 true, I);
4081 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4082 break;
4083 }
4084 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004085 }
4086 }
4087 }
4088
Chris Lattner6fc205f2006-05-05 06:39:07 +00004089 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004090 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4091 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4092 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4093 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004094 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004095 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004096 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4097 I.getType(), TD) &&
4098 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4099 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004100 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4101 Op1C->getOperand(0),
4102 I.getName());
4103 InsertNewInstBefore(NewOp, I);
4104 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4105 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004106 }
Chris Lattnere511b742006-11-14 07:46:50 +00004107
4108 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004109 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4110 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4111 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004112 SI0->getOperand(1) == SI1->getOperand(1) &&
4113 (SI0->hasOneUse() || SI1->hasOneUse())) {
4114 Instruction *NewOp =
4115 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4116 SI1->getOperand(0),
4117 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004118 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4119 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004120 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004121 }
4122
Chris Lattner99c65742007-10-24 05:38:08 +00004123 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4124 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4125 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4126 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4127 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4128 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4129 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4130 // If either of the constants are nans, then the whole thing returns
4131 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004132 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004133 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4134 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4135 RHS->getOperand(0));
4136 }
4137 }
4138 }
4139
Chris Lattner7e708292002-06-25 16:13:24 +00004140 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004141}
4142
Chris Lattnerafe91a52006-06-15 19:07:26 +00004143/// CollectBSwapParts - Look to see if the specified value defines a single byte
4144/// in the result. If it does, and if the specified byte hasn't been filled in
4145/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004146static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004147 Instruction *I = dyn_cast<Instruction>(V);
4148 if (I == 0) return true;
4149
4150 // If this is an or instruction, it is an inner node of the bswap.
4151 if (I->getOpcode() == Instruction::Or)
4152 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4153 CollectBSwapParts(I->getOperand(1), ByteValues);
4154
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004155 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004156 // If this is a shift by a constant int, and it is "24", then its operand
4157 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004158 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004159 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004160 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004161 8*(ByteValues.size()-1))
4162 return true;
4163
4164 unsigned DestNo;
4165 if (I->getOpcode() == Instruction::Shl) {
4166 // X << 24 defines the top byte with the lowest of the input bytes.
4167 DestNo = ByteValues.size()-1;
4168 } else {
4169 // X >>u 24 defines the low byte with the highest of the input bytes.
4170 DestNo = 0;
4171 }
4172
4173 // If the destination byte value is already defined, the values are or'd
4174 // together, which isn't a bswap (unless it's an or of the same bits).
4175 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4176 return true;
4177 ByteValues[DestNo] = I->getOperand(0);
4178 return false;
4179 }
4180
4181 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4182 // don't have this.
4183 Value *Shift = 0, *ShiftLHS = 0;
4184 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4185 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4186 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4187 return true;
4188 Instruction *SI = cast<Instruction>(Shift);
4189
4190 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004191 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4192 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004193 return true;
4194
4195 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4196 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004197 if (AndAmt->getValue().getActiveBits() > 64)
4198 return true;
4199 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004200 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004201 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004202 break;
4203 // Unknown mask for bswap.
4204 if (DestByte == ByteValues.size()) return true;
4205
Reid Spencerb83eb642006-10-20 07:07:24 +00004206 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004207 unsigned SrcByte;
4208 if (SI->getOpcode() == Instruction::Shl)
4209 SrcByte = DestByte - ShiftBytes;
4210 else
4211 SrcByte = DestByte + ShiftBytes;
4212
4213 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4214 if (SrcByte != ByteValues.size()-DestByte-1)
4215 return true;
4216
4217 // If the destination byte value is already defined, the values are or'd
4218 // together, which isn't a bswap (unless it's an or of the same bits).
4219 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4220 return true;
4221 ByteValues[DestByte] = SI->getOperand(0);
4222 return false;
4223}
4224
4225/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4226/// If so, insert the new bswap intrinsic and return it.
4227Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004228 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4229 if (!ITy || ITy->getBitWidth() % 16)
4230 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004231
4232 /// ByteValues - For each byte of the result, we keep track of which value
4233 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004234 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004235 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004236
4237 // Try to find all the pieces corresponding to the bswap.
4238 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4239 CollectBSwapParts(I.getOperand(1), ByteValues))
4240 return 0;
4241
4242 // Check to see if all of the bytes come from the same value.
4243 Value *V = ByteValues[0];
4244 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4245
4246 // Check to make sure that all of the bytes come from the same value.
4247 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4248 if (ByteValues[i] != V)
4249 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004250 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004251 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004252 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004253 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004254}
4255
4256
Chris Lattner7e708292002-06-25 16:13:24 +00004257Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004258 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004259 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004260
Chris Lattner42593e62007-03-24 23:56:43 +00004261 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004262 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004263
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004264 // or X, X = X
4265 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004266 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004267
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004268 // See if we can simplify any instructions used by the instruction whose sole
4269 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004270 if (!isa<VectorType>(I.getType())) {
4271 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4272 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4273 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4274 KnownZero, KnownOne))
4275 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004276 } else if (isa<ConstantAggregateZero>(Op1)) {
4277 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4278 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4279 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4280 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004281 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004282
4283
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004284
Chris Lattner3f5b8772002-05-06 16:14:14 +00004285 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004286 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004287 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004288 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4289 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004290 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004291 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004292 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004293 return BinaryOperator::createAnd(Or,
4294 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004295 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004296
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004297 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4298 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004299 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004300 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004301 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004302 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004303 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004304 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004305
4306 // Try to fold constant and into select arguments.
4307 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004308 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004309 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004310 if (isa<PHINode>(Op0))
4311 if (Instruction *NV = FoldOpIntoPhi(I))
4312 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004313 }
4314
Chris Lattner4f637d42006-01-06 17:59:59 +00004315 Value *A = 0, *B = 0;
4316 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004317
4318 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4319 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4320 return ReplaceInstUsesWith(I, Op1);
4321 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4322 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4323 return ReplaceInstUsesWith(I, Op0);
4324
Chris Lattner6423d4c2006-07-10 20:25:24 +00004325 // (A | B) | C and A | (B | C) -> bswap if possible.
4326 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004327 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004328 match(Op1, m_Or(m_Value(), m_Value())) ||
4329 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4330 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004331 if (Instruction *BSwap = MatchBSwap(I))
4332 return BSwap;
4333 }
4334
Chris Lattner6e4c6492005-05-09 04:58:36 +00004335 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4336 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004337 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004338 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4339 InsertNewInstBefore(NOr, I);
4340 NOr->takeName(Op0);
4341 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004342 }
4343
4344 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4345 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004346 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004347 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4348 InsertNewInstBefore(NOr, I);
4349 NOr->takeName(Op0);
4350 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004351 }
4352
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004353 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004354 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004355 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4356 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004357 Value *V1 = 0, *V2 = 0, *V3 = 0;
4358 C1 = dyn_cast<ConstantInt>(C);
4359 C2 = dyn_cast<ConstantInt>(D);
4360 if (C1 && C2) { // (A & C1)|(B & C2)
4361 // If we have: ((V + N) & C1) | (V & C2)
4362 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4363 // replace with V+N.
4364 if (C1->getValue() == ~C2->getValue()) {
4365 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4366 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4367 // Add commutes, try both ways.
4368 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4369 return ReplaceInstUsesWith(I, A);
4370 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4371 return ReplaceInstUsesWith(I, A);
4372 }
4373 // Or commutes, try both ways.
4374 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4375 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4376 // Add commutes, try both ways.
4377 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4378 return ReplaceInstUsesWith(I, B);
4379 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4380 return ReplaceInstUsesWith(I, B);
4381 }
4382 }
Chris Lattner044e5332007-04-08 08:01:49 +00004383 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004384 }
4385
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004386 // Check to see if we have any common things being and'ed. If so, find the
4387 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004388 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4389 if (A == B) // (A & C)|(A & D) == A & (C|D)
4390 V1 = A, V2 = C, V3 = D;
4391 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4392 V1 = A, V2 = B, V3 = C;
4393 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4394 V1 = C, V2 = A, V3 = D;
4395 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4396 V1 = C, V2 = A, V3 = B;
4397
4398 if (V1) {
4399 Value *Or =
4400 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4401 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004402 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004403 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004404 }
Chris Lattnere511b742006-11-14 07:46:50 +00004405
4406 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004407 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4408 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4409 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004410 SI0->getOperand(1) == SI1->getOperand(1) &&
4411 (SI0->hasOneUse() || SI1->hasOneUse())) {
4412 Instruction *NewOp =
4413 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4414 SI1->getOperand(0),
4415 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004416 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4417 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004418 }
4419 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004420
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004421 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4422 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004423 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004424 } else {
4425 A = 0;
4426 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004427 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004428 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4429 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004430 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004431
Misha Brukmancb6267b2004-07-30 12:50:08 +00004432 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004433 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4434 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4435 I.getName()+".demorgan"), I);
4436 return BinaryOperator::createNot(And);
4437 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004438 }
Chris Lattnera2881962003-02-18 19:28:33 +00004439
Reid Spencere4d87aa2006-12-23 06:05:41 +00004440 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4441 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4442 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004443 return R;
4444
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004445 Value *LHSVal, *RHSVal;
4446 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004447 ICmpInst::Predicate LHSCC, RHSCC;
4448 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4449 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4450 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4451 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4452 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4453 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4454 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004455 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4456 // We can't fold (ugt x, C) | (sgt x, C2).
4457 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004458 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004459 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004460 bool NeedsSwap;
4461 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004462 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004463 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004464 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004465
4466 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004467 std::swap(LHS, RHS);
4468 std::swap(LHSCst, RHSCst);
4469 std::swap(LHSCC, RHSCC);
4470 }
4471
Reid Spencere4d87aa2006-12-23 06:05:41 +00004472 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004473 // comparing a value against two constants and or'ing the result
4474 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004475 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4476 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004477 // equal.
4478 assert(LHSCst != RHSCst && "Compares not folded above?");
4479
4480 switch (LHSCC) {
4481 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004482 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004483 switch (RHSCC) {
4484 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004485 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004486 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4487 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4488 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4489 LHSVal->getName()+".off");
4490 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004491 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004492 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004493 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004494 break; // (X == 13 | X == 15) -> no change
4495 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4496 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004497 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004498 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4499 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4500 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004501 return ReplaceInstUsesWith(I, RHS);
4502 }
4503 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004504 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004505 switch (RHSCC) {
4506 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004507 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4508 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4509 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004510 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004511 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4512 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4513 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004514 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004515 }
4516 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004517 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004518 switch (RHSCC) {
4519 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004520 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004521 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004522 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004523 // If RHSCst is [us]MAXINT, it is always false. Not handling
4524 // this can cause overflow.
4525 if (RHSCst->isMaxValue(false))
4526 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004527 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4528 false, I);
4529 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4530 break;
4531 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4532 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004533 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004534 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4535 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004536 }
4537 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004538 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004539 switch (RHSCC) {
4540 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004541 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4542 break;
4543 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004544 // If RHSCst is [us]MAXINT, it is always false. Not handling
4545 // this can cause overflow.
4546 if (RHSCst->isMaxValue(true))
4547 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004548 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4549 false, I);
4550 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4551 break;
4552 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4553 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4554 return ReplaceInstUsesWith(I, RHS);
4555 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4556 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004557 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004558 break;
4559 case ICmpInst::ICMP_UGT:
4560 switch (RHSCC) {
4561 default: assert(0 && "Unknown integer condition code!");
4562 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4563 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4564 return ReplaceInstUsesWith(I, LHS);
4565 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4566 break;
4567 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4568 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004569 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004570 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4571 break;
4572 }
4573 break;
4574 case ICmpInst::ICMP_SGT:
4575 switch (RHSCC) {
4576 default: assert(0 && "Unknown integer condition code!");
4577 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4578 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4579 return ReplaceInstUsesWith(I, LHS);
4580 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4581 break;
4582 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4583 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004584 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004585 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4586 break;
4587 }
4588 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004589 }
4590 }
4591 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004592
4593 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004594 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004595 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004596 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004597 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4598 !isa<ICmpInst>(Op1C->getOperand(0))) {
4599 const Type *SrcTy = Op0C->getOperand(0)->getType();
4600 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4601 // Only do this if the casts both really cause code to be
4602 // generated.
4603 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4604 I.getType(), TD) &&
4605 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4606 I.getType(), TD)) {
4607 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4608 Op1C->getOperand(0),
4609 I.getName());
4610 InsertNewInstBefore(NewOp, I);
4611 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4612 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004613 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004614 }
Chris Lattner99c65742007-10-24 05:38:08 +00004615 }
4616
4617
4618 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4619 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4620 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4621 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004622 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4623 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004624 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4625 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4626 // If either of the constants are nans, then the whole thing returns
4627 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004628 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004629 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4630
4631 // Otherwise, no need to compare the two constants, compare the
4632 // rest.
4633 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4634 RHS->getOperand(0));
4635 }
4636 }
4637 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004638
Chris Lattner7e708292002-06-25 16:13:24 +00004639 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004640}
4641
Dan Gohman844731a2008-05-13 00:00:25 +00004642namespace {
4643
Chris Lattnerc317d392004-02-16 01:20:27 +00004644// XorSelf - Implements: X ^ X --> 0
4645struct XorSelf {
4646 Value *RHS;
4647 XorSelf(Value *rhs) : RHS(rhs) {}
4648 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4649 Instruction *apply(BinaryOperator &Xor) const {
4650 return &Xor;
4651 }
4652};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004653
Dan Gohman844731a2008-05-13 00:00:25 +00004654}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004655
Chris Lattner7e708292002-06-25 16:13:24 +00004656Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004657 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004658 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004659
Evan Chengd34af782008-03-25 20:07:13 +00004660 if (isa<UndefValue>(Op1)) {
4661 if (isa<UndefValue>(Op0))
4662 // Handle undef ^ undef -> 0 special case. This is a common
4663 // idiom (misuse).
4664 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004665 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004666 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004667
Chris Lattnerc317d392004-02-16 01:20:27 +00004668 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4669 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004670 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004671 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004672 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004673
4674 // See if we can simplify any instructions used by the instruction whose sole
4675 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004676 if (!isa<VectorType>(I.getType())) {
4677 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4678 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4679 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4680 KnownZero, KnownOne))
4681 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004682 } else if (isa<ConstantAggregateZero>(Op1)) {
4683 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004684 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004685
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004686 // Is this a ~ operation?
4687 if (Value *NotOp = dyn_castNotVal(&I)) {
4688 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4689 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4690 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4691 if (Op0I->getOpcode() == Instruction::And ||
4692 Op0I->getOpcode() == Instruction::Or) {
4693 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4694 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4695 Instruction *NotY =
4696 BinaryOperator::createNot(Op0I->getOperand(1),
4697 Op0I->getOperand(1)->getName()+".not");
4698 InsertNewInstBefore(NotY, I);
4699 if (Op0I->getOpcode() == Instruction::And)
4700 return BinaryOperator::createOr(Op0NotVal, NotY);
4701 else
4702 return BinaryOperator::createAnd(Op0NotVal, NotY);
4703 }
4704 }
4705 }
4706 }
4707
4708
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004709 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004710 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4711 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4712 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004713 return new ICmpInst(ICI->getInversePredicate(),
4714 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004715
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004716 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4717 return new FCmpInst(FCI->getInversePredicate(),
4718 FCI->getOperand(0), FCI->getOperand(1));
4719 }
4720
Reid Spencere4d87aa2006-12-23 06:05:41 +00004721 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004722 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004723 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4724 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004725 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4726 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004727 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004728 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004729 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004730
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004731 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004732 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004733 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004734 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004735 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4736 return BinaryOperator::createSub(
4737 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004738 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004739 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004740 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004741 // (X + C) ^ signbit -> (X + C + signbit)
4742 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4743 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004744
Chris Lattner7c4049c2004-01-12 19:35:11 +00004745 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004746 } else if (Op0I->getOpcode() == Instruction::Or) {
4747 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004748 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004749 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4750 // Anything in both C1 and C2 is known to be zero, remove it from
4751 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004752 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004753 NewRHS = ConstantExpr::getAnd(NewRHS,
4754 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004755 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004756 I.setOperand(0, Op0I->getOperand(0));
4757 I.setOperand(1, NewRHS);
4758 return &I;
4759 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004760 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004761 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004762 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004763
4764 // Try to fold constant and into select arguments.
4765 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004766 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004767 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004768 if (isa<PHINode>(Op0))
4769 if (Instruction *NV = FoldOpIntoPhi(I))
4770 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004771 }
4772
Chris Lattner8d969642003-03-10 23:06:50 +00004773 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004774 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004775 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004776
Chris Lattner8d969642003-03-10 23:06:50 +00004777 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004778 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004779 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004780
Chris Lattner318bf792007-03-18 22:51:34 +00004781
4782 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4783 if (Op1I) {
4784 Value *A, *B;
4785 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4786 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004787 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004788 I.swapOperands();
4789 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004790 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004791 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004792 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004793 }
Chris Lattner318bf792007-03-18 22:51:34 +00004794 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4795 if (Op0 == A) // A^(A^B) == B
4796 return ReplaceInstUsesWith(I, B);
4797 else if (Op0 == B) // A^(B^A) == B
4798 return ReplaceInstUsesWith(I, A);
4799 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004800 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004801 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004802 std::swap(A, B);
4803 }
Chris Lattner318bf792007-03-18 22:51:34 +00004804 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004805 I.swapOperands(); // Simplified below.
4806 std::swap(Op0, Op1);
4807 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004808 }
Chris Lattner318bf792007-03-18 22:51:34 +00004809 }
4810
4811 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4812 if (Op0I) {
4813 Value *A, *B;
4814 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4815 if (A == Op1) // (B|A)^B == (A|B)^B
4816 std::swap(A, B);
4817 if (B == Op1) { // (A|B)^B == A & ~B
4818 Instruction *NotB =
4819 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4820 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004821 }
Chris Lattner318bf792007-03-18 22:51:34 +00004822 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4823 if (Op1 == A) // (A^B)^A == B
4824 return ReplaceInstUsesWith(I, B);
4825 else if (Op1 == B) // (B^A)^A == B
4826 return ReplaceInstUsesWith(I, A);
4827 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4828 if (A == Op1) // (A&B)^A -> (B&A)^A
4829 std::swap(A, B);
4830 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004831 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004832 Instruction *N =
4833 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004834 return BinaryOperator::createAnd(N, Op1);
4835 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004836 }
Chris Lattner318bf792007-03-18 22:51:34 +00004837 }
4838
4839 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4840 if (Op0I && Op1I && Op0I->isShift() &&
4841 Op0I->getOpcode() == Op1I->getOpcode() &&
4842 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4843 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4844 Instruction *NewOp =
4845 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4846 Op1I->getOperand(0),
4847 Op0I->getName()), I);
4848 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4849 Op1I->getOperand(1));
4850 }
4851
4852 if (Op0I && Op1I) {
4853 Value *A, *B, *C, *D;
4854 // (A & B)^(A | B) -> A ^ B
4855 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4856 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4857 if ((A == C && B == D) || (A == D && B == C))
4858 return BinaryOperator::createXor(A, B);
4859 }
4860 // (A | B)^(A & B) -> A ^ B
4861 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4862 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4863 if ((A == C && B == D) || (A == D && B == C))
4864 return BinaryOperator::createXor(A, B);
4865 }
4866
4867 // (A & B)^(C & D)
4868 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4869 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4870 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4871 // (X & Y)^(X & Y) -> (Y^Z) & X
4872 Value *X = 0, *Y = 0, *Z = 0;
4873 if (A == C)
4874 X = A, Y = B, Z = D;
4875 else if (A == D)
4876 X = A, Y = B, Z = C;
4877 else if (B == C)
4878 X = B, Y = A, Z = D;
4879 else if (B == D)
4880 X = B, Y = A, Z = C;
4881
4882 if (X) {
4883 Instruction *NewOp =
4884 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4885 return BinaryOperator::createAnd(NewOp, X);
4886 }
4887 }
4888 }
4889
Reid Spencere4d87aa2006-12-23 06:05:41 +00004890 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4891 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4892 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004893 return R;
4894
Chris Lattner6fc205f2006-05-05 06:39:07 +00004895 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004896 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004897 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004898 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4899 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004900 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004901 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004902 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4903 I.getType(), TD) &&
4904 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4905 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004906 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4907 Op1C->getOperand(0),
4908 I.getName());
4909 InsertNewInstBefore(NewOp, I);
4910 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4911 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004912 }
Chris Lattner99c65742007-10-24 05:38:08 +00004913 }
Chris Lattner7e708292002-06-25 16:13:24 +00004914 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004915}
4916
Chris Lattnera96879a2004-09-29 17:40:11 +00004917/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4918/// overflowed for this type.
4919static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004920 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004921 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004922
Reid Spencere4e40032007-03-21 23:19:50 +00004923 if (IsSigned)
4924 if (In2->getValue().isNegative())
4925 return Result->getValue().sgt(In1->getValue());
4926 else
4927 return Result->getValue().slt(In1->getValue());
4928 else
4929 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004930}
4931
Chris Lattner574da9b2005-01-13 20:14:25 +00004932/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4933/// code necessary to compute the offset from the base pointer (without adding
4934/// in the base pointer). Return the result as a signed integer of intptr size.
4935static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4936 TargetData &TD = IC.getTargetData();
4937 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004938 const Type *IntPtrTy = TD.getIntPtrType();
4939 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004940
4941 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004942 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004943 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004944
Chris Lattner574da9b2005-01-13 20:14:25 +00004945 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4946 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004947 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004948 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4949 if (OpC->isZero()) continue;
4950
4951 // Handle a struct index, which adds its field offset to the pointer.
4952 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4953 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4954
4955 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4956 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004957 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004958 Result = IC.InsertNewInstBefore(
4959 BinaryOperator::createAdd(Result,
4960 ConstantInt::get(IntPtrTy, Size),
4961 GEP->getName()+".offs"), I);
4962 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004963 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004964
4965 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4966 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4967 Scale = ConstantExpr::getMul(OC, Scale);
4968 if (Constant *RC = dyn_cast<Constant>(Result))
4969 Result = ConstantExpr::getAdd(RC, Scale);
4970 else {
4971 // Emit an add instruction.
4972 Result = IC.InsertNewInstBefore(
4973 BinaryOperator::createAdd(Result, Scale,
4974 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004975 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004976 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004977 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004978 // Convert to correct type.
4979 if (Op->getType() != IntPtrTy) {
4980 if (Constant *OpC = dyn_cast<Constant>(Op))
4981 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4982 else
4983 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4984 Op->getName()+".c"), I);
4985 }
4986 if (Size != 1) {
4987 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4988 if (Constant *OpC = dyn_cast<Constant>(Op))
4989 Op = ConstantExpr::getMul(OpC, Scale);
4990 else // We'll let instcombine(mul) convert this to a shl if possible.
4991 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4992 GEP->getName()+".idx"), I);
4993 }
4994
4995 // Emit an add instruction.
4996 if (isa<Constant>(Op) && isa<Constant>(Result))
4997 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4998 cast<Constant>(Result));
4999 else
5000 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
5001 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005002 }
5003 return Result;
5004}
5005
Chris Lattner10c0d912008-04-22 02:53:33 +00005006
5007/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5008/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5009/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5010/// complex, and scales are involved. The above expression would also be legal
5011/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5012/// later form is less amenable to optimization though, and we are allowed to
5013/// generate the first by knowing that pointer arithmetic doesn't overflow.
5014///
5015/// If we can't emit an optimized form for this expression, this returns null.
5016///
5017static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5018 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005019 TargetData &TD = IC.getTargetData();
5020 gep_type_iterator GTI = gep_type_begin(GEP);
5021
5022 // Check to see if this gep only has a single variable index. If so, and if
5023 // any constant indices are a multiple of its scale, then we can compute this
5024 // in terms of the scale of the variable index. For example, if the GEP
5025 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5026 // because the expression will cross zero at the same point.
5027 unsigned i, e = GEP->getNumOperands();
5028 int64_t Offset = 0;
5029 for (i = 1; i != e; ++i, ++GTI) {
5030 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5031 // Compute the aggregate offset of constant indices.
5032 if (CI->isZero()) continue;
5033
5034 // Handle a struct index, which adds its field offset to the pointer.
5035 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5036 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5037 } else {
5038 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5039 Offset += Size*CI->getSExtValue();
5040 }
5041 } else {
5042 // Found our variable index.
5043 break;
5044 }
5045 }
5046
5047 // If there are no variable indices, we must have a constant offset, just
5048 // evaluate it the general way.
5049 if (i == e) return 0;
5050
5051 Value *VariableIdx = GEP->getOperand(i);
5052 // Determine the scale factor of the variable element. For example, this is
5053 // 4 if the variable index is into an array of i32.
5054 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5055
5056 // Verify that there are no other variable indices. If so, emit the hard way.
5057 for (++i, ++GTI; i != e; ++i, ++GTI) {
5058 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5059 if (!CI) return 0;
5060
5061 // Compute the aggregate offset of constant indices.
5062 if (CI->isZero()) continue;
5063
5064 // Handle a struct index, which adds its field offset to the pointer.
5065 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5066 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5067 } else {
5068 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5069 Offset += Size*CI->getSExtValue();
5070 }
5071 }
5072
5073 // Okay, we know we have a single variable index, which must be a
5074 // pointer/array/vector index. If there is no offset, life is simple, return
5075 // the index.
5076 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5077 if (Offset == 0) {
5078 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5079 // we don't need to bother extending: the extension won't affect where the
5080 // computation crosses zero.
5081 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5082 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5083 VariableIdx->getNameStart(), &I);
5084 return VariableIdx;
5085 }
5086
5087 // Otherwise, there is an index. The computation we will do will be modulo
5088 // the pointer size, so get it.
5089 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5090
5091 Offset &= PtrSizeMask;
5092 VariableScale &= PtrSizeMask;
5093
5094 // To do this transformation, any constant index must be a multiple of the
5095 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5096 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5097 // multiple of the variable scale.
5098 int64_t NewOffs = Offset / (int64_t)VariableScale;
5099 if (Offset != NewOffs*(int64_t)VariableScale)
5100 return 0;
5101
5102 // Okay, we can do this evaluation. Start by converting the index to intptr.
5103 const Type *IntPtrTy = TD.getIntPtrType();
5104 if (VariableIdx->getType() != IntPtrTy)
5105 VariableIdx = CastInst::createIntegerCast(VariableIdx, IntPtrTy,
5106 true /*SExt*/,
5107 VariableIdx->getNameStart(), &I);
5108 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5109 return BinaryOperator::createAdd(VariableIdx, OffsetVal, "offset", &I);
5110}
5111
5112
Reid Spencere4d87aa2006-12-23 06:05:41 +00005113/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005114/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005115Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5116 ICmpInst::Predicate Cond,
5117 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005118 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005119
Chris Lattner10c0d912008-04-22 02:53:33 +00005120 // Look through bitcasts.
5121 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5122 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005123
Chris Lattner574da9b2005-01-13 20:14:25 +00005124 Value *PtrBase = GEPLHS->getOperand(0);
5125 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005126 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005127 // This transformation (ignoring the base and scales) is valid because we
5128 // know pointers can't overflow. See if we can output an optimized form.
5129 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5130
5131 // If not, synthesize the offset the hard way.
5132 if (Offset == 0)
5133 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005134 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5135 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005136 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005137 // If the base pointers are different, but the indices are the same, just
5138 // compare the base pointer.
5139 if (PtrBase != GEPRHS->getOperand(0)) {
5140 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005141 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005142 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005143 if (IndicesTheSame)
5144 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5145 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5146 IndicesTheSame = false;
5147 break;
5148 }
5149
5150 // If all indices are the same, just compare the base pointers.
5151 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005152 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5153 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005154
5155 // Otherwise, the base pointers are different and the indices are
5156 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005157 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005158 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005159
Chris Lattnere9d782b2005-01-13 22:25:21 +00005160 // If one of the GEPs has all zero indices, recurse.
5161 bool AllZeros = true;
5162 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5163 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5164 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5165 AllZeros = false;
5166 break;
5167 }
5168 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005169 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5170 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005171
5172 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005173 AllZeros = true;
5174 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5175 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5176 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5177 AllZeros = false;
5178 break;
5179 }
5180 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005181 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005182
Chris Lattner4401c9c2005-01-14 00:20:05 +00005183 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5184 // If the GEPs only differ by one index, compare it.
5185 unsigned NumDifferences = 0; // Keep track of # differences.
5186 unsigned DiffOperand = 0; // The operand that differs.
5187 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5188 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005189 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5190 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005191 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005192 NumDifferences = 2;
5193 break;
5194 } else {
5195 if (NumDifferences++) break;
5196 DiffOperand = i;
5197 }
5198 }
5199
5200 if (NumDifferences == 0) // SAME GEP?
5201 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005202 ConstantInt::get(Type::Int1Ty,
5203 isTrueWhenEqual(Cond)));
5204
Chris Lattner4401c9c2005-01-14 00:20:05 +00005205 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005206 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5207 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005208 // Make sure we do a signed comparison here.
5209 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005210 }
5211 }
5212
Reid Spencere4d87aa2006-12-23 06:05:41 +00005213 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005214 // the result to fold to a constant!
5215 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5216 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5217 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5218 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5219 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005220 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005221 }
5222 }
5223 return 0;
5224}
5225
Reid Spencere4d87aa2006-12-23 06:05:41 +00005226Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5227 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005228 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005229
Chris Lattner58e97462007-01-14 19:42:17 +00005230 // Fold trivial predicates.
5231 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5232 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5233 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5234 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5235
5236 // Simplify 'fcmp pred X, X'
5237 if (Op0 == Op1) {
5238 switch (I.getPredicate()) {
5239 default: assert(0 && "Unknown predicate!");
5240 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5241 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5242 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5243 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5244 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5245 case FCmpInst::FCMP_OLT: // True if ordered and less than
5246 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5247 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5248
5249 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5250 case FCmpInst::FCMP_ULT: // True if unordered or less than
5251 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5252 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5253 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5254 I.setPredicate(FCmpInst::FCMP_UNO);
5255 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5256 return &I;
5257
5258 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5259 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5260 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5261 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5262 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5263 I.setPredicate(FCmpInst::FCMP_ORD);
5264 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5265 return &I;
5266 }
5267 }
5268
Reid Spencere4d87aa2006-12-23 06:05:41 +00005269 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005270 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005271
Reid Spencere4d87aa2006-12-23 06:05:41 +00005272 // Handle fcmp with constant RHS
5273 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5274 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5275 switch (LHSI->getOpcode()) {
5276 case Instruction::PHI:
5277 if (Instruction *NV = FoldOpIntoPhi(I))
5278 return NV;
5279 break;
5280 case Instruction::Select:
5281 // If either operand of the select is a constant, we can fold the
5282 // comparison into the select arms, which will cause one to be
5283 // constant folded and the select turned into a bitwise or.
5284 Value *Op1 = 0, *Op2 = 0;
5285 if (LHSI->hasOneUse()) {
5286 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5287 // Fold the known value into the constant operand.
5288 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5289 // Insert a new FCmp of the other select operand.
5290 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5291 LHSI->getOperand(2), RHSC,
5292 I.getName()), I);
5293 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5294 // Fold the known value into the constant operand.
5295 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5296 // Insert a new FCmp of the other select operand.
5297 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5298 LHSI->getOperand(1), RHSC,
5299 I.getName()), I);
5300 }
5301 }
5302
5303 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005304 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005305 break;
5306 }
5307 }
5308
5309 return Changed ? &I : 0;
5310}
5311
5312Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5313 bool Changed = SimplifyCompare(I);
5314 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5315 const Type *Ty = Op0->getType();
5316
5317 // icmp X, X
5318 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005319 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5320 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005321
5322 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005323 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005324
Reid Spencere4d87aa2006-12-23 06:05:41 +00005325 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005326 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005327 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5328 isa<ConstantPointerNull>(Op0)) &&
5329 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005330 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005331 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5332 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00005333
Reid Spencere4d87aa2006-12-23 06:05:41 +00005334 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005335 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005336 switch (I.getPredicate()) {
5337 default: assert(0 && "Invalid icmp instruction!");
5338 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00005339 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005340 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005341 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005342 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005343 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00005344 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005345
Reid Spencere4d87aa2006-12-23 06:05:41 +00005346 case ICmpInst::ICMP_UGT:
5347 case ICmpInst::ICMP_SGT:
5348 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005349 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005350 case ICmpInst::ICMP_ULT:
5351 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00005352 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5353 InsertNewInstBefore(Not, I);
5354 return BinaryOperator::createAnd(Not, Op1);
5355 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005356 case ICmpInst::ICMP_UGE:
5357 case ICmpInst::ICMP_SGE:
5358 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005359 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005360 case ICmpInst::ICMP_ULE:
5361 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00005362 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5363 InsertNewInstBefore(Not, I);
5364 return BinaryOperator::createOr(Not, Op1);
5365 }
5366 }
Chris Lattner8b170942002-08-09 23:47:40 +00005367 }
5368
Chris Lattner2be51ae2004-06-09 04:24:29 +00005369 // See if we are doing a comparison between a constant and an instruction that
5370 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005371 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005372 Value *A, *B;
5373
Chris Lattnerb6566012008-01-05 01:18:20 +00005374 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5375 if (I.isEquality() && CI->isNullValue() &&
5376 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5377 // (icmp cond A B) if cond is equality
5378 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005379 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005380
Reid Spencere4d87aa2006-12-23 06:05:41 +00005381 switch (I.getPredicate()) {
5382 default: break;
5383 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5384 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005385 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005386 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5387 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5388 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5389 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005390 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5391 if (CI->isMinValue(true))
5392 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5393 ConstantInt::getAllOnesValue(Op0->getType()));
5394
Reid Spencere4d87aa2006-12-23 06:05:41 +00005395 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005396
Reid Spencere4d87aa2006-12-23 06:05:41 +00005397 case ICmpInst::ICMP_SLT:
5398 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005399 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005400 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5401 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5402 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5403 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5404 break;
5405
5406 case ICmpInst::ICMP_UGT:
5407 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005408 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005409 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5410 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5411 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5412 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005413
5414 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5415 if (CI->isMaxValue(true))
5416 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5417 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005418 break;
5419
5420 case ICmpInst::ICMP_SGT:
5421 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005422 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005423 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5424 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5425 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5426 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5427 break;
5428
5429 case ICmpInst::ICMP_ULE:
5430 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005431 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005432 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5433 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5434 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5435 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5436 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005437
Reid Spencere4d87aa2006-12-23 06:05:41 +00005438 case ICmpInst::ICMP_SLE:
5439 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005440 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005441 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5442 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5443 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5444 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5445 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005446
Reid Spencere4d87aa2006-12-23 06:05:41 +00005447 case ICmpInst::ICMP_UGE:
5448 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005449 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005450 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5451 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5452 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5453 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5454 break;
5455
5456 case ICmpInst::ICMP_SGE:
5457 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005458 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005459 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5460 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5461 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5462 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5463 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005464 }
5465
Reid Spencere4d87aa2006-12-23 06:05:41 +00005466 // If we still have a icmp le or icmp ge instruction, turn it into the
5467 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005468 // already been handled above, this requires little checking.
5469 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005470 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005471 default: break;
5472 case ICmpInst::ICMP_ULE:
5473 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5474 case ICmpInst::ICMP_SLE:
5475 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5476 case ICmpInst::ICMP_UGE:
5477 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5478 case ICmpInst::ICMP_SGE:
5479 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005480 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005481
5482 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005483 // in the input. If this comparison is a normal comparison, it demands all
5484 // bits, if it is a sign bit comparison, it only demands the sign bit.
5485
5486 bool UnusedBit;
5487 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5488
Reid Spencer0460fb32007-03-22 20:36:03 +00005489 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5490 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005491 if (SimplifyDemandedBits(Op0,
5492 isSignBit ? APInt::getSignBit(BitWidth)
5493 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005494 KnownZero, KnownOne, 0))
5495 return &I;
5496
5497 // Given the known and unknown bits, compute a range that the LHS could be
5498 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005499 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005500 // Compute the Min, Max and RHS values based on the known bits. For the
5501 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005502 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5503 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005504 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005505 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5506 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005507 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005508 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5509 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005510 }
5511 switch (I.getPredicate()) { // LE/GE have been folded already.
5512 default: assert(0 && "Unknown icmp opcode!");
5513 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005514 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005515 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005516 break;
5517 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005518 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005519 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005520 break;
5521 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005522 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005523 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005524 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005525 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005526 break;
5527 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005528 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005529 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005530 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005531 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005532 break;
5533 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005534 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005535 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005536 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005537 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005538 break;
5539 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005540 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005541 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005542 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005543 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005544 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005545 }
5546 }
5547
Reid Spencere4d87aa2006-12-23 06:05:41 +00005548 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005549 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005550 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005551 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005552 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5553 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005554 }
5555
Chris Lattner01deb9d2007-04-03 17:43:25 +00005556 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005557 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5558 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5559 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005560 case Instruction::GetElementPtr:
5561 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005562 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005563 bool isAllZeros = true;
5564 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5565 if (!isa<Constant>(LHSI->getOperand(i)) ||
5566 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5567 isAllZeros = false;
5568 break;
5569 }
5570 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005571 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005572 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5573 }
5574 break;
5575
Chris Lattner6970b662005-04-23 15:31:55 +00005576 case Instruction::PHI:
5577 if (Instruction *NV = FoldOpIntoPhi(I))
5578 return NV;
5579 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005580 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005581 // If either operand of the select is a constant, we can fold the
5582 // comparison into the select arms, which will cause one to be
5583 // constant folded and the select turned into a bitwise or.
5584 Value *Op1 = 0, *Op2 = 0;
5585 if (LHSI->hasOneUse()) {
5586 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5587 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005588 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5589 // Insert a new ICmp of the other select operand.
5590 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5591 LHSI->getOperand(2), RHSC,
5592 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005593 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5594 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005595 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5596 // Insert a new ICmp of the other select operand.
5597 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5598 LHSI->getOperand(1), RHSC,
5599 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005600 }
5601 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005602
Chris Lattner6970b662005-04-23 15:31:55 +00005603 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005604 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005605 break;
5606 }
Chris Lattner4802d902007-04-06 18:57:34 +00005607 case Instruction::Malloc:
5608 // If we have (malloc != null), and if the malloc has a single use, we
5609 // can assume it is successful and remove the malloc.
5610 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5611 AddToWorkList(LHSI);
5612 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5613 !isTrueWhenEqual(I)));
5614 }
5615 break;
5616 }
Chris Lattner6970b662005-04-23 15:31:55 +00005617 }
5618
Reid Spencere4d87aa2006-12-23 06:05:41 +00005619 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005620 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005621 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005622 return NI;
5623 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005624 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5625 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005626 return NI;
5627
Reid Spencere4d87aa2006-12-23 06:05:41 +00005628 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005629 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5630 // now.
5631 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5632 if (isa<PointerType>(Op0->getType()) &&
5633 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005634 // We keep moving the cast from the left operand over to the right
5635 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005636 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005637
Chris Lattner57d86372007-01-06 01:45:59 +00005638 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5639 // so eliminate it as well.
5640 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5641 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005642
Chris Lattnerde90b762003-11-03 04:25:02 +00005643 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005644 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005645 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005646 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005647 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005648 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005649 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005650 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005651 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005652 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005653 }
Chris Lattner57d86372007-01-06 01:45:59 +00005654 }
5655
5656 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005657 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005658 // This comes up when you have code like
5659 // int X = A < B;
5660 // if (X) ...
5661 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005662 // with a constant or another cast from the same type.
5663 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005664 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005665 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005666 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005667
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005668 // ~x < ~y --> y < x
5669 { Value *A, *B;
5670 if (match(Op0, m_Not(m_Value(A))) &&
5671 match(Op1, m_Not(m_Value(B))))
5672 return new ICmpInst(I.getPredicate(), B, A);
5673 }
5674
Chris Lattner65b72ba2006-09-18 04:22:48 +00005675 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005676 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005677
5678 // -x == -y --> x == y
5679 if (match(Op0, m_Neg(m_Value(A))) &&
5680 match(Op1, m_Neg(m_Value(B))))
5681 return new ICmpInst(I.getPredicate(), A, B);
5682
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005683 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5684 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5685 Value *OtherVal = A == Op1 ? B : A;
5686 return new ICmpInst(I.getPredicate(), OtherVal,
5687 Constant::getNullValue(A->getType()));
5688 }
5689
5690 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5691 // A^c1 == C^c2 --> A == C^(c1^c2)
5692 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5693 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5694 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005695 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005696 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5697 return new ICmpInst(I.getPredicate(), A,
5698 InsertNewInstBefore(Xor, I));
5699 }
5700
5701 // A^B == A^D -> B == D
5702 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5703 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5704 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5705 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5706 }
5707 }
5708
5709 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5710 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005711 // A == (A^B) -> B == 0
5712 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005713 return new ICmpInst(I.getPredicate(), OtherVal,
5714 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005715 }
5716 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005717 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005718 return new ICmpInst(I.getPredicate(), B,
5719 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005720 }
5721 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005722 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005723 return new ICmpInst(I.getPredicate(), B,
5724 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005725 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005726
Chris Lattner9c2328e2006-11-14 06:06:06 +00005727 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5728 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5729 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5730 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5731 Value *X = 0, *Y = 0, *Z = 0;
5732
5733 if (A == C) {
5734 X = B; Y = D; Z = A;
5735 } else if (A == D) {
5736 X = B; Y = C; Z = A;
5737 } else if (B == C) {
5738 X = A; Y = D; Z = B;
5739 } else if (B == D) {
5740 X = A; Y = C; Z = B;
5741 }
5742
5743 if (X) { // Build (X^Y) & Z
5744 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5745 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5746 I.setOperand(0, Op1);
5747 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5748 return &I;
5749 }
5750 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005751 }
Chris Lattner7e708292002-06-25 16:13:24 +00005752 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005753}
5754
Chris Lattner562ef782007-06-20 23:46:26 +00005755
5756/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5757/// and CmpRHS are both known to be integer constants.
5758Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5759 ConstantInt *DivRHS) {
5760 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5761 const APInt &CmpRHSV = CmpRHS->getValue();
5762
5763 // FIXME: If the operand types don't match the type of the divide
5764 // then don't attempt this transform. The code below doesn't have the
5765 // logic to deal with a signed divide and an unsigned compare (and
5766 // vice versa). This is because (x /s C1) <s C2 produces different
5767 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5768 // (x /u C1) <u C2. Simply casting the operands and result won't
5769 // work. :( The if statement below tests that condition and bails
5770 // if it finds it.
5771 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5772 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5773 return 0;
5774 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005775 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005776
5777 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5778 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5779 // C2 (CI). By solving for X we can turn this into a range check
5780 // instead of computing a divide.
5781 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5782
5783 // Determine if the product overflows by seeing if the product is
5784 // not equal to the divide. Make sure we do the same kind of divide
5785 // as in the LHS instruction that we're folding.
5786 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5787 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5788
5789 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005790 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005791
Chris Lattner1dbfd482007-06-21 18:11:19 +00005792 // Figure out the interval that is being checked. For example, a comparison
5793 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5794 // Compute this interval based on the constants involved and the signedness of
5795 // the compare/divide. This computes a half-open interval, keeping track of
5796 // whether either value in the interval overflows. After analysis each
5797 // overflow variable is set to 0 if it's corresponding bound variable is valid
5798 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5799 int LoOverflow = 0, HiOverflow = 0;
5800 ConstantInt *LoBound = 0, *HiBound = 0;
5801
5802
Chris Lattner562ef782007-06-20 23:46:26 +00005803 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005804 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005805 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005806 HiOverflow = LoOverflow = ProdOV;
5807 if (!HiOverflow)
5808 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005809 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005810 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005811 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005812 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5813 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005814 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005815 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5816 HiOverflow = LoOverflow = ProdOV;
5817 if (!HiOverflow)
5818 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005819 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005820 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005821 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5822 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005823 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005824 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005825 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005826 }
Dan Gohman76491272008-02-13 22:09:18 +00005827 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005828 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005829 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005830 LoBound = AddOne(DivRHS);
5831 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005832 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5833 HiOverflow = 1; // [INTMIN+1, overflow)
5834 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5835 }
Dan Gohman76491272008-02-13 22:09:18 +00005836 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005837 // e.g. X/-5 op 3 --> [-19, -14)
5838 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005839 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005840 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005841 HiBound = AddOne(Prod);
5842 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005843 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005844 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005845 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005846 HiBound = Subtract(Prod, DivRHS);
5847 }
5848
Chris Lattner1dbfd482007-06-21 18:11:19 +00005849 // Dividing by a negative swaps the condition. LT <-> GT
5850 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005851 }
5852
5853 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005854 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005855 default: assert(0 && "Unhandled icmp opcode!");
5856 case ICmpInst::ICMP_EQ:
5857 if (LoOverflow && HiOverflow)
5858 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5859 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005860 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005861 ICmpInst::ICMP_UGE, X, LoBound);
5862 else if (LoOverflow)
5863 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5864 ICmpInst::ICMP_ULT, X, HiBound);
5865 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005866 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005867 case ICmpInst::ICMP_NE:
5868 if (LoOverflow && HiOverflow)
5869 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5870 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005871 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005872 ICmpInst::ICMP_ULT, X, LoBound);
5873 else if (LoOverflow)
5874 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5875 ICmpInst::ICMP_UGE, X, HiBound);
5876 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005877 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005878 case ICmpInst::ICMP_ULT:
5879 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005880 if (LoOverflow == +1) // Low bound is greater than input range.
5881 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5882 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005883 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005884 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005885 case ICmpInst::ICMP_UGT:
5886 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005887 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005888 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005889 else if (HiOverflow == -1) // High bound less than input range.
5890 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5891 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005892 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5893 else
5894 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5895 }
5896}
5897
5898
Chris Lattner01deb9d2007-04-03 17:43:25 +00005899/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5900///
5901Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5902 Instruction *LHSI,
5903 ConstantInt *RHS) {
5904 const APInt &RHSV = RHS->getValue();
5905
5906 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005907 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005908 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5909 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5910 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005911 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5912 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005913 Value *CompareVal = LHSI->getOperand(0);
5914
5915 // If the sign bit of the XorCST is not set, there is no change to
5916 // the operation, just stop using the Xor.
5917 if (!XorCST->getValue().isNegative()) {
5918 ICI.setOperand(0, CompareVal);
5919 AddToWorkList(LHSI);
5920 return &ICI;
5921 }
5922
5923 // Was the old condition true if the operand is positive?
5924 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5925
5926 // If so, the new one isn't.
5927 isTrueIfPositive ^= true;
5928
5929 if (isTrueIfPositive)
5930 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5931 else
5932 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5933 }
5934 }
5935 break;
5936 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5937 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5938 LHSI->getOperand(0)->hasOneUse()) {
5939 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5940
5941 // If the LHS is an AND of a truncating cast, we can widen the
5942 // and/compare to be the input width without changing the value
5943 // produced, eliminating a cast.
5944 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5945 // We can do this transformation if either the AND constant does not
5946 // have its sign bit set or if it is an equality comparison.
5947 // Extending a relational comparison when we're checking the sign
5948 // bit would not work.
5949 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005950 (ICI.isEquality() ||
5951 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005952 uint32_t BitWidth =
5953 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5954 APInt NewCST = AndCST->getValue();
5955 NewCST.zext(BitWidth);
5956 APInt NewCI = RHSV;
5957 NewCI.zext(BitWidth);
5958 Instruction *NewAnd =
5959 BinaryOperator::createAnd(Cast->getOperand(0),
5960 ConstantInt::get(NewCST),LHSI->getName());
5961 InsertNewInstBefore(NewAnd, ICI);
5962 return new ICmpInst(ICI.getPredicate(), NewAnd,
5963 ConstantInt::get(NewCI));
5964 }
5965 }
5966
5967 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5968 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5969 // happens a LOT in code produced by the C front-end, for bitfield
5970 // access.
5971 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5972 if (Shift && !Shift->isShift())
5973 Shift = 0;
5974
5975 ConstantInt *ShAmt;
5976 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5977 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5978 const Type *AndTy = AndCST->getType(); // Type of the and.
5979
5980 // We can fold this as long as we can't shift unknown bits
5981 // into the mask. This can only happen with signed shift
5982 // rights, as they sign-extend.
5983 if (ShAmt) {
5984 bool CanFold = Shift->isLogicalShift();
5985 if (!CanFold) {
5986 // To test for the bad case of the signed shr, see if any
5987 // of the bits shifted in could be tested after the mask.
5988 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5989 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5990
5991 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5992 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5993 AndCST->getValue()) == 0)
5994 CanFold = true;
5995 }
5996
5997 if (CanFold) {
5998 Constant *NewCst;
5999 if (Shift->getOpcode() == Instruction::Shl)
6000 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6001 else
6002 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6003
6004 // Check to see if we are shifting out any of the bits being
6005 // compared.
6006 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6007 // If we shifted bits out, the fold is not going to work out.
6008 // As a special case, check to see if this means that the
6009 // result is always true or false now.
6010 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6011 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6012 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6013 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6014 } else {
6015 ICI.setOperand(1, NewCst);
6016 Constant *NewAndCST;
6017 if (Shift->getOpcode() == Instruction::Shl)
6018 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6019 else
6020 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6021 LHSI->setOperand(1, NewAndCST);
6022 LHSI->setOperand(0, Shift->getOperand(0));
6023 AddToWorkList(Shift); // Shift is dead.
6024 AddUsesToWorkList(ICI);
6025 return &ICI;
6026 }
6027 }
6028 }
6029
6030 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6031 // preferable because it allows the C<<Y expression to be hoisted out
6032 // of a loop if Y is invariant and X is not.
6033 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6034 ICI.isEquality() && !Shift->isArithmeticShift() &&
6035 isa<Instruction>(Shift->getOperand(0))) {
6036 // Compute C << Y.
6037 Value *NS;
6038 if (Shift->getOpcode() == Instruction::LShr) {
6039 NS = BinaryOperator::createShl(AndCST,
6040 Shift->getOperand(1), "tmp");
6041 } else {
6042 // Insert a logical shift.
6043 NS = BinaryOperator::createLShr(AndCST,
6044 Shift->getOperand(1), "tmp");
6045 }
6046 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6047
6048 // Compute X & (C << Y).
6049 Instruction *NewAnd =
6050 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
6051 InsertNewInstBefore(NewAnd, ICI);
6052
6053 ICI.setOperand(0, NewAnd);
6054 return &ICI;
6055 }
6056 }
6057 break;
6058
Chris Lattnera0141b92007-07-15 20:42:37 +00006059 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6060 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6061 if (!ShAmt) break;
6062
6063 uint32_t TypeBits = RHSV.getBitWidth();
6064
6065 // Check that the shift amount is in range. If not, don't perform
6066 // undefined shifts. When the shift is visited it will be
6067 // simplified.
6068 if (ShAmt->uge(TypeBits))
6069 break;
6070
6071 if (ICI.isEquality()) {
6072 // If we are comparing against bits always shifted out, the
6073 // comparison cannot succeed.
6074 Constant *Comp =
6075 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6076 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6077 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6078 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6079 return ReplaceInstUsesWith(ICI, Cst);
6080 }
6081
6082 if (LHSI->hasOneUse()) {
6083 // Otherwise strength reduce the shift into an and.
6084 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6085 Constant *Mask =
6086 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006087
Chris Lattnera0141b92007-07-15 20:42:37 +00006088 Instruction *AndI =
6089 BinaryOperator::createAnd(LHSI->getOperand(0),
6090 Mask, LHSI->getName()+".mask");
6091 Value *And = InsertNewInstBefore(AndI, ICI);
6092 return new ICmpInst(ICI.getPredicate(), And,
6093 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006094 }
6095 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006096
6097 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6098 bool TrueIfSigned = false;
6099 if (LHSI->hasOneUse() &&
6100 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6101 // (X << 31) <s 0 --> (X&1) != 0
6102 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6103 (TypeBits-ShAmt->getZExtValue()-1));
6104 Instruction *AndI =
6105 BinaryOperator::createAnd(LHSI->getOperand(0),
6106 Mask, LHSI->getName()+".mask");
6107 Value *And = InsertNewInstBefore(AndI, ICI);
6108
6109 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6110 And, Constant::getNullValue(And->getType()));
6111 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006112 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006113 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006114
6115 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006116 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006117 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006118 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006119 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006120
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006121 // Check that the shift amount is in range. If not, don't perform
6122 // undefined shifts. When the shift is visited it will be
6123 // simplified.
6124 uint32_t TypeBits = RHSV.getBitWidth();
6125 if (ShAmt->uge(TypeBits))
6126 break;
6127
6128 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006129
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006130 // If we are comparing against bits always shifted out, the
6131 // comparison cannot succeed.
6132 APInt Comp = RHSV << ShAmtVal;
6133 if (LHSI->getOpcode() == Instruction::LShr)
6134 Comp = Comp.lshr(ShAmtVal);
6135 else
6136 Comp = Comp.ashr(ShAmtVal);
6137
6138 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6139 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6140 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6141 return ReplaceInstUsesWith(ICI, Cst);
6142 }
6143
6144 // Otherwise, check to see if the bits shifted out are known to be zero.
6145 // If so, we can compare against the unshifted value:
6146 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006147 if (LHSI->hasOneUse() &&
6148 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006149 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6150 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6151 ConstantExpr::getShl(RHS, ShAmt));
6152 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006153
Evan Chengf30752c2008-04-23 00:38:06 +00006154 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006155 // Otherwise strength reduce the shift into an and.
6156 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6157 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006158
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006159 Instruction *AndI =
6160 BinaryOperator::createAnd(LHSI->getOperand(0),
6161 Mask, LHSI->getName()+".mask");
6162 Value *And = InsertNewInstBefore(AndI, ICI);
6163 return new ICmpInst(ICI.getPredicate(), And,
6164 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006165 }
6166 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006167 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006168
6169 case Instruction::SDiv:
6170 case Instruction::UDiv:
6171 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6172 // Fold this div into the comparison, producing a range check.
6173 // Determine, based on the divide type, what the range is being
6174 // checked. If there is an overflow on the low or high side, remember
6175 // it, otherwise compute the range [low, hi) bounding the new value.
6176 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006177 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6178 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6179 DivRHS))
6180 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006181 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006182
6183 case Instruction::Add:
6184 // Fold: icmp pred (add, X, C1), C2
6185
6186 if (!ICI.isEquality()) {
6187 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6188 if (!LHSC) break;
6189 const APInt &LHSV = LHSC->getValue();
6190
6191 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6192 .subtract(LHSV);
6193
6194 if (ICI.isSignedPredicate()) {
6195 if (CR.getLower().isSignBit()) {
6196 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6197 ConstantInt::get(CR.getUpper()));
6198 } else if (CR.getUpper().isSignBit()) {
6199 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6200 ConstantInt::get(CR.getLower()));
6201 }
6202 } else {
6203 if (CR.getLower().isMinValue()) {
6204 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6205 ConstantInt::get(CR.getUpper()));
6206 } else if (CR.getUpper().isMinValue()) {
6207 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6208 ConstantInt::get(CR.getLower()));
6209 }
6210 }
6211 }
6212 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006213 }
6214
6215 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6216 if (ICI.isEquality()) {
6217 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6218
6219 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6220 // the second operand is a constant, simplify a bit.
6221 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6222 switch (BO->getOpcode()) {
6223 case Instruction::SRem:
6224 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6225 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6226 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6227 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6228 Instruction *NewRem =
6229 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
6230 BO->getName());
6231 InsertNewInstBefore(NewRem, ICI);
6232 return new ICmpInst(ICI.getPredicate(), NewRem,
6233 Constant::getNullValue(BO->getType()));
6234 }
6235 }
6236 break;
6237 case Instruction::Add:
6238 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6239 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6240 if (BO->hasOneUse())
6241 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6242 Subtract(RHS, BOp1C));
6243 } else if (RHSV == 0) {
6244 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6245 // efficiently invertible, or if the add has just this one use.
6246 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6247
6248 if (Value *NegVal = dyn_castNegVal(BOp1))
6249 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6250 else if (Value *NegVal = dyn_castNegVal(BOp0))
6251 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6252 else if (BO->hasOneUse()) {
6253 Instruction *Neg = BinaryOperator::createNeg(BOp1);
6254 InsertNewInstBefore(Neg, ICI);
6255 Neg->takeName(BO);
6256 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6257 }
6258 }
6259 break;
6260 case Instruction::Xor:
6261 // For the xor case, we can xor two constants together, eliminating
6262 // the explicit xor.
6263 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6264 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6265 ConstantExpr::getXor(RHS, BOC));
6266
6267 // FALLTHROUGH
6268 case Instruction::Sub:
6269 // Replace (([sub|xor] A, B) != 0) with (A != B)
6270 if (RHSV == 0)
6271 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6272 BO->getOperand(1));
6273 break;
6274
6275 case Instruction::Or:
6276 // If bits are being or'd in that are not present in the constant we
6277 // are comparing against, then the comparison could never succeed!
6278 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6279 Constant *NotCI = ConstantExpr::getNot(RHS);
6280 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6281 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6282 isICMP_NE));
6283 }
6284 break;
6285
6286 case Instruction::And:
6287 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6288 // If bits are being compared against that are and'd out, then the
6289 // comparison can never succeed!
6290 if ((RHSV & ~BOC->getValue()) != 0)
6291 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6292 isICMP_NE));
6293
6294 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6295 if (RHS == BOC && RHSV.isPowerOf2())
6296 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6297 ICmpInst::ICMP_NE, LHSI,
6298 Constant::getNullValue(RHS->getType()));
6299
6300 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6301 if (isSignBit(BOC)) {
6302 Value *X = BO->getOperand(0);
6303 Constant *Zero = Constant::getNullValue(X->getType());
6304 ICmpInst::Predicate pred = isICMP_NE ?
6305 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6306 return new ICmpInst(pred, X, Zero);
6307 }
6308
6309 // ((X & ~7) == 0) --> X < 8
6310 if (RHSV == 0 && isHighOnes(BOC)) {
6311 Value *X = BO->getOperand(0);
6312 Constant *NegX = ConstantExpr::getNeg(BOC);
6313 ICmpInst::Predicate pred = isICMP_NE ?
6314 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6315 return new ICmpInst(pred, X, NegX);
6316 }
6317 }
6318 default: break;
6319 }
6320 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6321 // Handle icmp {eq|ne} <intrinsic>, intcst.
6322 if (II->getIntrinsicID() == Intrinsic::bswap) {
6323 AddToWorkList(II);
6324 ICI.setOperand(0, II->getOperand(1));
6325 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6326 return &ICI;
6327 }
6328 }
6329 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006330 // If the LHS is a cast from an integral value of the same size,
6331 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006332 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6333 Value *CastOp = Cast->getOperand(0);
6334 const Type *SrcTy = CastOp->getType();
6335 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6336 if (SrcTy->isInteger() &&
6337 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6338 // If this is an unsigned comparison, try to make the comparison use
6339 // smaller constant values.
6340 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6341 // X u< 128 => X s> -1
6342 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6343 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6344 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6345 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6346 // X u> 127 => X s< 0
6347 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6348 Constant::getNullValue(SrcTy));
6349 }
6350 }
6351 }
6352 }
6353 return 0;
6354}
6355
6356/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6357/// We only handle extending casts so far.
6358///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006359Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6360 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006361 Value *LHSCIOp = LHSCI->getOperand(0);
6362 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006363 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006364 Value *RHSCIOp;
6365
Chris Lattner8c756c12007-05-05 22:41:33 +00006366 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6367 // integer type is the same size as the pointer type.
6368 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6369 getTargetData().getPointerSizeInBits() ==
6370 cast<IntegerType>(DestTy)->getBitWidth()) {
6371 Value *RHSOp = 0;
6372 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006373 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006374 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6375 RHSOp = RHSC->getOperand(0);
6376 // If the pointer types don't match, insert a bitcast.
6377 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006378 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006379 }
6380
6381 if (RHSOp)
6382 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6383 }
6384
6385 // The code below only handles extension cast instructions, so far.
6386 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006387 if (LHSCI->getOpcode() != Instruction::ZExt &&
6388 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006389 return 0;
6390
Reid Spencere4d87aa2006-12-23 06:05:41 +00006391 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6392 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006393
Reid Spencere4d87aa2006-12-23 06:05:41 +00006394 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006395 // Not an extension from the same type?
6396 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006397 if (RHSCIOp->getType() != LHSCIOp->getType())
6398 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006399
Nick Lewycky4189a532008-01-28 03:48:02 +00006400 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006401 // and the other is a zext), then we can't handle this.
6402 if (CI->getOpcode() != LHSCI->getOpcode())
6403 return 0;
6404
Nick Lewycky4189a532008-01-28 03:48:02 +00006405 // Deal with equality cases early.
6406 if (ICI.isEquality())
6407 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6408
6409 // A signed comparison of sign extended values simplifies into a
6410 // signed comparison.
6411 if (isSignedCmp && isSignedExt)
6412 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6413
6414 // The other three cases all fold into an unsigned comparison.
6415 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006416 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006417
Reid Spencere4d87aa2006-12-23 06:05:41 +00006418 // If we aren't dealing with a constant on the RHS, exit early
6419 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6420 if (!CI)
6421 return 0;
6422
6423 // Compute the constant that would happen if we truncated to SrcTy then
6424 // reextended to DestTy.
6425 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6426 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6427
6428 // If the re-extended constant didn't change...
6429 if (Res2 == CI) {
6430 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6431 // For example, we might have:
6432 // %A = sext short %X to uint
6433 // %B = icmp ugt uint %A, 1330
6434 // It is incorrect to transform this into
6435 // %B = icmp ugt short %X, 1330
6436 // because %A may have negative value.
6437 //
6438 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6439 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006440 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006441 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6442 else
6443 return 0;
6444 }
6445
6446 // The re-extended constant changed so the constant cannot be represented
6447 // in the shorter type. Consequently, we cannot emit a simple comparison.
6448
6449 // First, handle some easy cases. We know the result cannot be equal at this
6450 // point so handle the ICI.isEquality() cases
6451 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006452 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006453 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006454 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006455
6456 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6457 // should have been folded away previously and not enter in here.
6458 Value *Result;
6459 if (isSignedCmp) {
6460 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006461 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006462 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006463 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006464 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006465 } else {
6466 // We're performing an unsigned comparison.
6467 if (isSignedExt) {
6468 // We're performing an unsigned comp with a sign extended value.
6469 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006470 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006471 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6472 NegOne, ICI.getName()), ICI);
6473 } else {
6474 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006475 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006476 }
6477 }
6478
6479 // Finally, return the value computed.
6480 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6481 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6482 return ReplaceInstUsesWith(ICI, Result);
6483 } else {
6484 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6485 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6486 "ICmp should be folded!");
6487 if (Constant *CI = dyn_cast<Constant>(Result))
6488 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6489 else
6490 return BinaryOperator::createNot(Result);
6491 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006492}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006493
Reid Spencer832254e2007-02-02 02:16:23 +00006494Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6495 return commonShiftTransforms(I);
6496}
6497
6498Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6499 return commonShiftTransforms(I);
6500}
6501
6502Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006503 if (Instruction *R = commonShiftTransforms(I))
6504 return R;
6505
6506 Value *Op0 = I.getOperand(0);
6507
6508 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6509 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6510 if (CSI->isAllOnesValue())
6511 return ReplaceInstUsesWith(I, CSI);
6512
6513 // See if we can turn a signed shr into an unsigned shr.
6514 if (MaskedValueIsZero(Op0,
6515 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6516 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6517
6518 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006519}
6520
6521Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6522 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006523 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006524
6525 // shl X, 0 == X and shr X, 0 == X
6526 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006527 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006528 Op0 == Constant::getNullValue(Op0->getType()))
6529 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006530
Reid Spencere4d87aa2006-12-23 06:05:41 +00006531 if (isa<UndefValue>(Op0)) {
6532 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006533 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006534 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006535 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6536 }
6537 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006538 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6539 return ReplaceInstUsesWith(I, Op0);
6540 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006541 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006542 }
6543
Chris Lattner2eefe512004-04-09 19:05:30 +00006544 // Try to fold constant and into select arguments.
6545 if (isa<Constant>(Op0))
6546 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006547 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006548 return R;
6549
Reid Spencerb83eb642006-10-20 07:07:24 +00006550 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006551 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6552 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006553 return 0;
6554}
6555
Reid Spencerb83eb642006-10-20 07:07:24 +00006556Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006557 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006558 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006559
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006560 // See if we can simplify any instructions used by the instruction whose sole
6561 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006562 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6563 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6564 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006565 KnownZero, KnownOne))
6566 return &I;
6567
Chris Lattner4d5542c2006-01-06 07:12:35 +00006568 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6569 // of a signed value.
6570 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006571 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006572 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006573 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6574 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006575 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006576 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006577 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006578 }
6579
6580 // ((X*C1) << C2) == (X * (C1 << C2))
6581 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6582 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6583 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6584 return BinaryOperator::createMul(BO->getOperand(0),
6585 ConstantExpr::getShl(BOOp, Op1));
6586
6587 // Try to fold constant and into select arguments.
6588 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6589 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6590 return R;
6591 if (isa<PHINode>(Op0))
6592 if (Instruction *NV = FoldOpIntoPhi(I))
6593 return NV;
6594
Chris Lattner8999dd32007-12-22 09:07:47 +00006595 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6596 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6597 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6598 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6599 // place. Don't try to do this transformation in this case. Also, we
6600 // require that the input operand is a shift-by-constant so that we have
6601 // confidence that the shifts will get folded together. We could do this
6602 // xform in more cases, but it is unlikely to be profitable.
6603 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6604 isa<ConstantInt>(TrOp->getOperand(1))) {
6605 // Okay, we'll do this xform. Make the shift of shift.
6606 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6607 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6608 I.getName());
6609 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6610
6611 // For logical shifts, the truncation has the effect of making the high
6612 // part of the register be zeros. Emulate this by inserting an AND to
6613 // clear the top bits as needed. This 'and' will usually be zapped by
6614 // other xforms later if dead.
6615 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6616 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6617 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6618
6619 // The mask we constructed says what the trunc would do if occurring
6620 // between the shifts. We want to know the effect *after* the second
6621 // shift. We know that it is a logical shift by a constant, so adjust the
6622 // mask as appropriate.
6623 if (I.getOpcode() == Instruction::Shl)
6624 MaskV <<= Op1->getZExtValue();
6625 else {
6626 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6627 MaskV = MaskV.lshr(Op1->getZExtValue());
6628 }
6629
6630 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6631 TI->getName());
6632 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6633
6634 // Return the value truncated to the interesting size.
6635 return new TruncInst(And, I.getType());
6636 }
6637 }
6638
Chris Lattner4d5542c2006-01-06 07:12:35 +00006639 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006640 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6641 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6642 Value *V1, *V2;
6643 ConstantInt *CC;
6644 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006645 default: break;
6646 case Instruction::Add:
6647 case Instruction::And:
6648 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006649 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006650 // These operators commute.
6651 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006652 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6653 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006654 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006655 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006656 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006657 Op0BO->getName());
6658 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006659 Instruction *X =
6660 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6661 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006662 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006663 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006664 return BinaryOperator::createAnd(X, ConstantInt::get(
6665 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006666 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006667
Chris Lattner150f12a2005-09-18 06:30:59 +00006668 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006669 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006670 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006671 match(Op0BOOp1,
6672 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006673 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6674 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006675 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006676 Op0BO->getOperand(0), Op1,
6677 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006678 InsertNewInstBefore(YS, I); // (Y << C)
6679 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006680 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006681 V1->getName()+".mask");
6682 InsertNewInstBefore(XM, I); // X & (CC << C)
6683
6684 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6685 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006686 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006687
Reid Spencera07cb7d2007-02-02 14:41:37 +00006688 // FALL THROUGH.
6689 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006690 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006691 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6692 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006693 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006694 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006695 Op0BO->getOperand(1), Op1,
6696 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006697 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006698 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006699 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006700 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006701 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006702 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006703 return BinaryOperator::createAnd(X, ConstantInt::get(
6704 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006705 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006706
Chris Lattner13d4ab42006-05-31 21:14:00 +00006707 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006708 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6709 match(Op0BO->getOperand(0),
6710 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006711 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006712 cast<BinaryOperator>(Op0BO->getOperand(0))
6713 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006714 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006715 Op0BO->getOperand(1), Op1,
6716 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006717 InsertNewInstBefore(YS, I); // (Y << C)
6718 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006719 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006720 V1->getName()+".mask");
6721 InsertNewInstBefore(XM, I); // X & (CC << C)
6722
Chris Lattner13d4ab42006-05-31 21:14:00 +00006723 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006724 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006725
Chris Lattner11021cb2005-09-18 05:12:10 +00006726 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006727 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006728 }
6729
6730
6731 // If the operand is an bitwise operator with a constant RHS, and the
6732 // shift is the only use, we can pull it out of the shift.
6733 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6734 bool isValid = true; // Valid only for And, Or, Xor
6735 bool highBitSet = false; // Transform if high bit of constant set?
6736
6737 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006738 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006739 case Instruction::Add:
6740 isValid = isLeftShift;
6741 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006742 case Instruction::Or:
6743 case Instruction::Xor:
6744 highBitSet = false;
6745 break;
6746 case Instruction::And:
6747 highBitSet = true;
6748 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006749 }
6750
6751 // If this is a signed shift right, and the high bit is modified
6752 // by the logical operation, do not perform the transformation.
6753 // The highBitSet boolean indicates the value of the high bit of
6754 // the constant which would cause it to be modified for this
6755 // operation.
6756 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006757 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006758 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006759
6760 if (isValid) {
6761 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6762
6763 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006764 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006765 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006766 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006767
6768 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6769 NewRHS);
6770 }
6771 }
6772 }
6773 }
6774
Chris Lattnerad0124c2006-01-06 07:52:12 +00006775 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006776 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6777 if (ShiftOp && !ShiftOp->isShift())
6778 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006779
Reid Spencerb83eb642006-10-20 07:07:24 +00006780 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006781 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006782 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6783 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006784 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6785 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6786 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006787
Zhou Sheng4351c642007-04-02 08:20:41 +00006788 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006789 if (AmtSum > TypeBits)
6790 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006791
6792 const IntegerType *Ty = cast<IntegerType>(I.getType());
6793
6794 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006795 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006796 return BinaryOperator::create(I.getOpcode(), X,
6797 ConstantInt::get(Ty, AmtSum));
6798 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6799 I.getOpcode() == Instruction::AShr) {
6800 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6801 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6802 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6803 I.getOpcode() == Instruction::LShr) {
6804 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6805 Instruction *Shift =
6806 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6807 InsertNewInstBefore(Shift, I);
6808
Zhou Shenge9e03f62007-03-28 15:02:20 +00006809 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006810 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006811 }
6812
Chris Lattnerb87056f2007-02-05 00:57:54 +00006813 // Okay, if we get here, one shift must be left, and the other shift must be
6814 // right. See if the amounts are equal.
6815 if (ShiftAmt1 == ShiftAmt2) {
6816 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6817 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006818 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006819 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006820 }
6821 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6822 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006823 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006824 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006825 }
6826 // We can simplify ((X << C) >>s C) into a trunc + sext.
6827 // NOTE: we could do this for any C, but that would make 'unusual' integer
6828 // types. For now, just stick to ones well-supported by the code
6829 // generators.
6830 const Type *SExtType = 0;
6831 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006832 case 1 :
6833 case 8 :
6834 case 16 :
6835 case 32 :
6836 case 64 :
6837 case 128:
6838 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6839 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006840 default: break;
6841 }
6842 if (SExtType) {
6843 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6844 InsertNewInstBefore(NewTrunc, I);
6845 return new SExtInst(NewTrunc, Ty);
6846 }
6847 // Otherwise, we can't handle it yet.
6848 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006849 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006850
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006851 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006852 if (I.getOpcode() == Instruction::Shl) {
6853 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6854 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006855 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006856 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006857 InsertNewInstBefore(Shift, I);
6858
Reid Spencer55702aa2007-03-25 21:11:44 +00006859 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6860 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006861 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006862
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006863 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006864 if (I.getOpcode() == Instruction::LShr) {
6865 assert(ShiftOp->getOpcode() == Instruction::Shl);
6866 Instruction *Shift =
6867 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6868 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006869
Reid Spencerd5e30f02007-03-26 17:18:58 +00006870 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006871 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006872 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006873
6874 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6875 } else {
6876 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006877 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006878
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006879 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006880 if (I.getOpcode() == Instruction::Shl) {
6881 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6882 ShiftOp->getOpcode() == Instruction::AShr);
6883 Instruction *Shift =
6884 BinaryOperator::create(ShiftOp->getOpcode(), X,
6885 ConstantInt::get(Ty, ShiftDiff));
6886 InsertNewInstBefore(Shift, I);
6887
Reid Spencer55702aa2007-03-25 21:11:44 +00006888 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006889 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006890 }
6891
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006892 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006893 if (I.getOpcode() == Instruction::LShr) {
6894 assert(ShiftOp->getOpcode() == Instruction::Shl);
6895 Instruction *Shift =
6896 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6897 InsertNewInstBefore(Shift, I);
6898
Reid Spencer68d27cf2007-03-26 23:45:51 +00006899 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006900 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006901 }
6902
6903 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006904 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006905 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006906 return 0;
6907}
6908
Chris Lattnera1be5662002-05-02 17:06:02 +00006909
Chris Lattnercfd65102005-10-29 04:36:15 +00006910/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6911/// expression. If so, decompose it, returning some value X, such that Val is
6912/// X*Scale+Offset.
6913///
6914static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006915 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006916 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006917 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006918 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006919 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006920 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006921 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6922 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6923 if (I->getOpcode() == Instruction::Shl) {
6924 // This is a value scaled by '1 << the shift amt'.
6925 Scale = 1U << RHS->getZExtValue();
6926 Offset = 0;
6927 return I->getOperand(0);
6928 } else if (I->getOpcode() == Instruction::Mul) {
6929 // This value is scaled by 'RHS'.
6930 Scale = RHS->getZExtValue();
6931 Offset = 0;
6932 return I->getOperand(0);
6933 } else if (I->getOpcode() == Instruction::Add) {
6934 // We have X+C. Check to see if we really have (X*C2)+C1,
6935 // where C1 is divisible by C2.
6936 unsigned SubScale;
6937 Value *SubVal =
6938 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6939 Offset += RHS->getZExtValue();
6940 Scale = SubScale;
6941 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006942 }
6943 }
6944 }
6945
6946 // Otherwise, we can't look past this.
6947 Scale = 1;
6948 Offset = 0;
6949 return Val;
6950}
6951
6952
Chris Lattnerb3f83972005-10-24 06:03:58 +00006953/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6954/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006955Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006956 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006957 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006958
Chris Lattnerb53c2382005-10-24 06:22:12 +00006959 // Remove any uses of AI that are dead.
6960 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006961
Chris Lattnerb53c2382005-10-24 06:22:12 +00006962 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6963 Instruction *User = cast<Instruction>(*UI++);
6964 if (isInstructionTriviallyDead(User)) {
6965 while (UI != E && *UI == User)
6966 ++UI; // If this instruction uses AI more than once, don't break UI.
6967
Chris Lattnerb53c2382005-10-24 06:22:12 +00006968 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006969 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006970 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006971 }
6972 }
6973
Chris Lattnerb3f83972005-10-24 06:03:58 +00006974 // Get the type really allocated and the type casted to.
6975 const Type *AllocElTy = AI.getAllocatedType();
6976 const Type *CastElTy = PTy->getElementType();
6977 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006978
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006979 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6980 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006981 if (CastElTyAlign < AllocElTyAlign) return 0;
6982
Chris Lattner39387a52005-10-24 06:35:18 +00006983 // If the allocation has multiple uses, only promote it if we are strictly
6984 // increasing the alignment of the resultant allocation. If we keep it the
6985 // same, we open the door to infinite loops of various kinds.
6986 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6987
Duncan Sands514ab342007-11-01 20:53:16 +00006988 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6989 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006990 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006991
Chris Lattner455fcc82005-10-29 03:19:53 +00006992 // See if we can satisfy the modulus by pulling a scale out of the array
6993 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006994 unsigned ArraySizeScale;
6995 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006996 Value *NumElements = // See if the array size is a decomposable linear expr.
6997 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6998
Chris Lattner455fcc82005-10-29 03:19:53 +00006999 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7000 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007001 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7002 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007003
Chris Lattner455fcc82005-10-29 03:19:53 +00007004 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7005 Value *Amt = 0;
7006 if (Scale == 1) {
7007 Amt = NumElements;
7008 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007009 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007010 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7011 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007012 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007013 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007014 else if (Scale != 1) {
7015 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
7016 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007017 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007018 }
7019
Jeff Cohen86796be2007-04-04 16:58:57 +00007020 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7021 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00007022 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
7023 Amt = InsertNewInstBefore(Tmp, AI);
7024 }
7025
Chris Lattnerb3f83972005-10-24 06:03:58 +00007026 AllocationInst *New;
7027 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007028 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007029 else
Chris Lattner6934a042007-02-11 01:23:03 +00007030 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007031 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007032 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007033
7034 // If the allocation has multiple uses, insert a cast and change all things
7035 // that used it to use the new cast. This will also hack on CI, but it will
7036 // die soon.
7037 if (!AI.hasOneUse()) {
7038 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007039 // New is the allocation instruction, pointer typed. AI is the original
7040 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7041 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007042 InsertNewInstBefore(NewCast, AI);
7043 AI.replaceAllUsesWith(NewCast);
7044 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007045 return ReplaceInstUsesWith(CI, New);
7046}
7047
Chris Lattner70074e02006-05-13 02:06:03 +00007048/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007049/// and return it as type Ty without inserting any new casts and without
7050/// changing the computed value. This is used by code that tries to decide
7051/// whether promoting or shrinking integer operations to wider or smaller types
7052/// will allow us to eliminate a truncate or extend.
7053///
7054/// This is a truncation operation if Ty is smaller than V->getType(), or an
7055/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007056bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7057 unsigned CastOpc,
7058 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007059 // We can always evaluate constants in another type.
7060 if (isa<ConstantInt>(V))
7061 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007062
7063 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007064 if (!I) return false;
7065
7066 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007067
Chris Lattner951626b2007-08-02 06:11:14 +00007068 // If this is an extension or truncate, we can often eliminate it.
7069 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7070 // If this is a cast from the destination type, we can trivially eliminate
7071 // it, and this will remove a cast overall.
7072 if (I->getOperand(0)->getType() == Ty) {
7073 // If the first operand is itself a cast, and is eliminable, do not count
7074 // this as an eliminable cast. We would prefer to eliminate those two
7075 // casts first.
7076 if (!isa<CastInst>(I->getOperand(0)))
7077 ++NumCastsRemoved;
7078 return true;
7079 }
7080 }
7081
7082 // We can't extend or shrink something that has multiple uses: doing so would
7083 // require duplicating the instruction in general, which isn't profitable.
7084 if (!I->hasOneUse()) return false;
7085
Chris Lattner70074e02006-05-13 02:06:03 +00007086 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007087 case Instruction::Add:
7088 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007089 case Instruction::And:
7090 case Instruction::Or:
7091 case Instruction::Xor:
7092 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007093 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7094 NumCastsRemoved) &&
7095 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7096 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007097
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007098 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007099 // A multiply can be truncated by truncating its operands.
7100 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7101 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7102 NumCastsRemoved) &&
7103 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7104 NumCastsRemoved);
7105
Chris Lattner46b96052006-11-29 07:18:39 +00007106 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007107 // If we are truncating the result of this SHL, and if it's a shift of a
7108 // constant amount, we can always perform a SHL in a smaller type.
7109 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007110 uint32_t BitWidth = Ty->getBitWidth();
7111 if (BitWidth < OrigTy->getBitWidth() &&
7112 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007113 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7114 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007115 }
7116 break;
7117 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007118 // If this is a truncate of a logical shr, we can truncate it to a smaller
7119 // lshr iff we know that the bits we would otherwise be shifting in are
7120 // already zeros.
7121 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007122 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7123 uint32_t BitWidth = Ty->getBitWidth();
7124 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007125 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007126 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7127 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007128 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7129 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007130 }
7131 }
Chris Lattner46b96052006-11-29 07:18:39 +00007132 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007133 case Instruction::ZExt:
7134 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007135 case Instruction::Trunc:
7136 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007137 // can safely replace it. Note that replacing it does not reduce the number
7138 // of casts in the input.
7139 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007140 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007141
Reid Spencer3da59db2006-11-27 01:05:10 +00007142 break;
7143 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007144 // TODO: Can handle more cases here.
7145 break;
7146 }
7147
7148 return false;
7149}
7150
7151/// EvaluateInDifferentType - Given an expression that
7152/// CanEvaluateInDifferentType returns true for, actually insert the code to
7153/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007154Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007155 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007156 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007157 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007158
7159 // Otherwise, it must be an instruction.
7160 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007161 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007162 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007163 case Instruction::Add:
7164 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007165 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007166 case Instruction::And:
7167 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007168 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007169 case Instruction::AShr:
7170 case Instruction::LShr:
7171 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007172 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007173 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7174 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
7175 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007176 break;
7177 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007178 case Instruction::Trunc:
7179 case Instruction::ZExt:
7180 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007181 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007182 // just return the source. There's no need to insert it because it is not
7183 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007184 if (I->getOperand(0)->getType() == Ty)
7185 return I->getOperand(0);
7186
Chris Lattner951626b2007-08-02 06:11:14 +00007187 // Otherwise, must be the same type of case, so just reinsert a new one.
7188 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7189 Ty, I->getName());
7190 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007191 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007192 // TODO: Can handle more cases here.
7193 assert(0 && "Unreachable!");
7194 break;
7195 }
7196
7197 return InsertNewInstBefore(Res, *I);
7198}
7199
Reid Spencer3da59db2006-11-27 01:05:10 +00007200/// @brief Implement the transforms common to all CastInst visitors.
7201Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007202 Value *Src = CI.getOperand(0);
7203
Dan Gohman23d9d272007-05-11 21:10:54 +00007204 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007205 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007206 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007207 if (Instruction::CastOps opc =
7208 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7209 // The first cast (CSrc) is eliminable so we need to fix up or replace
7210 // the second cast (CI). CSrc will then have a good chance of being dead.
7211 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007212 }
7213 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007214
Reid Spencer3da59db2006-11-27 01:05:10 +00007215 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007216 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7217 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7218 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007219
7220 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007221 if (isa<PHINode>(Src))
7222 if (Instruction *NV = FoldOpIntoPhi(CI))
7223 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007224
Reid Spencer3da59db2006-11-27 01:05:10 +00007225 return 0;
7226}
7227
Chris Lattnerd3e28342007-04-27 17:44:50 +00007228/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7229Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7230 Value *Src = CI.getOperand(0);
7231
Chris Lattnerd3e28342007-04-27 17:44:50 +00007232 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007233 // If casting the result of a getelementptr instruction with no offset, turn
7234 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007235 if (GEP->hasAllZeroIndices()) {
7236 // Changing the cast operand is usually not a good idea but it is safe
7237 // here because the pointer operand is being replaced with another
7238 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007239 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007240 CI.setOperand(0, GEP->getOperand(0));
7241 return &CI;
7242 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007243
7244 // If the GEP has a single use, and the base pointer is a bitcast, and the
7245 // GEP computes a constant offset, see if we can convert these three
7246 // instructions into fewer. This typically happens with unions and other
7247 // non-type-safe code.
7248 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7249 if (GEP->hasAllConstantIndices()) {
7250 // We are guaranteed to get a constant from EmitGEPOffset.
7251 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7252 int64_t Offset = OffsetV->getSExtValue();
7253
7254 // Get the base pointer input of the bitcast, and the type it points to.
7255 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7256 const Type *GEPIdxTy =
7257 cast<PointerType>(OrigBase->getType())->getElementType();
7258 if (GEPIdxTy->isSized()) {
7259 SmallVector<Value*, 8> NewIndices;
7260
Chris Lattnerc42e2262007-05-05 01:59:31 +00007261 // Start with the index over the outer type. Note that the type size
7262 // might be zero (even if the offset isn't zero) if the indexed type
7263 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007264 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007265 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007266 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007267 FirstIdx = Offset/TySize;
7268 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007269
Chris Lattnerc42e2262007-05-05 01:59:31 +00007270 // Handle silly modulus not returning values values [0..TySize).
7271 if (Offset < 0) {
7272 --FirstIdx;
7273 Offset += TySize;
7274 assert(Offset >= 0);
7275 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007276 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007277 }
7278
7279 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007280
7281 // Index into the types. If we fail, set OrigBase to null.
7282 while (Offset) {
7283 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7284 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007285 if (Offset < (int64_t)SL->getSizeInBytes()) {
7286 unsigned Elt = SL->getElementContainingOffset(Offset);
7287 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007288
Chris Lattner6b6aef82007-05-15 00:16:00 +00007289 Offset -= SL->getElementOffset(Elt);
7290 GEPIdxTy = STy->getElementType(Elt);
7291 } else {
7292 // Otherwise, we can't index into this, bail out.
7293 Offset = 0;
7294 OrigBase = 0;
7295 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007296 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7297 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007298 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007299 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7300 Offset %= EltSize;
7301 } else {
7302 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7303 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007304 GEPIdxTy = STy->getElementType();
7305 } else {
7306 // Otherwise, we can't index into this, bail out.
7307 Offset = 0;
7308 OrigBase = 0;
7309 }
7310 }
7311 if (OrigBase) {
7312 // If we were able to index down into an element, create the GEP
7313 // and bitcast the result. This eliminates one bitcast, potentially
7314 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007315 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7316 NewIndices.begin(),
7317 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007318 InsertNewInstBefore(NGEP, CI);
7319 NGEP->takeName(GEP);
7320
Chris Lattner9bc14642007-04-28 00:57:34 +00007321 if (isa<BitCastInst>(CI))
7322 return new BitCastInst(NGEP, CI.getType());
7323 assert(isa<PtrToIntInst>(CI));
7324 return new PtrToIntInst(NGEP, CI.getType());
7325 }
7326 }
7327 }
7328 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007329 }
7330
7331 return commonCastTransforms(CI);
7332}
7333
7334
7335
Chris Lattnerc739cd62007-03-03 05:27:34 +00007336/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7337/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007338/// cases.
7339/// @brief Implement the transforms common to CastInst with integer operands
7340Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7341 if (Instruction *Result = commonCastTransforms(CI))
7342 return Result;
7343
7344 Value *Src = CI.getOperand(0);
7345 const Type *SrcTy = Src->getType();
7346 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007347 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7348 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007349
Reid Spencer3da59db2006-11-27 01:05:10 +00007350 // See if we can simplify any instructions used by the LHS whose sole
7351 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007352 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7353 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007354 KnownZero, KnownOne))
7355 return &CI;
7356
7357 // If the source isn't an instruction or has more than one use then we
7358 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007359 Instruction *SrcI = dyn_cast<Instruction>(Src);
7360 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007361 return 0;
7362
Chris Lattnerc739cd62007-03-03 05:27:34 +00007363 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007364 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007365 if (!isa<BitCastInst>(CI) &&
7366 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007367 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007368 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007369 // eliminates the cast, so it is always a win. If this is a zero-extension,
7370 // we need to do an AND to maintain the clear top-part of the computation,
7371 // so we require that the input have eliminated at least one cast. If this
7372 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007373 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007374 bool DoXForm;
7375 switch (CI.getOpcode()) {
7376 default:
7377 // All the others use floating point so we shouldn't actually
7378 // get here because of the check above.
7379 assert(0 && "Unknown cast type");
7380 case Instruction::Trunc:
7381 DoXForm = true;
7382 break;
7383 case Instruction::ZExt:
7384 DoXForm = NumCastsRemoved >= 1;
7385 break;
7386 case Instruction::SExt:
7387 DoXForm = NumCastsRemoved >= 2;
7388 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007389 }
7390
7391 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007392 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7393 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007394 assert(Res->getType() == DestTy);
7395 switch (CI.getOpcode()) {
7396 default: assert(0 && "Unknown cast type!");
7397 case Instruction::Trunc:
7398 case Instruction::BitCast:
7399 // Just replace this cast with the result.
7400 return ReplaceInstUsesWith(CI, Res);
7401 case Instruction::ZExt: {
7402 // We need to emit an AND to clear the high bits.
7403 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007404 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7405 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00007406 return BinaryOperator::createAnd(Res, C);
7407 }
7408 case Instruction::SExt:
7409 // We need to emit a cast to truncate, then a cast to sext.
7410 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007411 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7412 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007413 }
7414 }
7415 }
7416
7417 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7418 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7419
7420 switch (SrcI->getOpcode()) {
7421 case Instruction::Add:
7422 case Instruction::Mul:
7423 case Instruction::And:
7424 case Instruction::Or:
7425 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007426 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007427 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7428 // Don't insert two casts if they cannot be eliminated. We allow
7429 // two casts to be inserted if the sizes are the same. This could
7430 // only be converting signedness, which is a noop.
7431 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007432 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7433 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007434 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007435 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7436 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7437 return BinaryOperator::create(
7438 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007439 }
7440 }
7441
7442 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7443 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7444 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007445 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007446 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007447 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007448 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7449 }
7450 break;
7451 case Instruction::SDiv:
7452 case Instruction::UDiv:
7453 case Instruction::SRem:
7454 case Instruction::URem:
7455 // If we are just changing the sign, rewrite.
7456 if (DestBitSize == SrcBitSize) {
7457 // Don't insert two casts if they cannot be eliminated. We allow
7458 // two casts to be inserted if the sizes are the same. This could
7459 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007460 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7461 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007462 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7463 Op0, DestTy, SrcI);
7464 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7465 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007466 return BinaryOperator::create(
7467 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7468 }
7469 }
7470 break;
7471
7472 case Instruction::Shl:
7473 // Allow changing the sign of the source operand. Do not allow
7474 // changing the size of the shift, UNLESS the shift amount is a
7475 // constant. We must not change variable sized shifts to a smaller
7476 // size, because it is undefined to shift more bits out than exist
7477 // in the value.
7478 if (DestBitSize == SrcBitSize ||
7479 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007480 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7481 Instruction::BitCast : Instruction::Trunc);
7482 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007483 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007484 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007485 }
7486 break;
7487 case Instruction::AShr:
7488 // If this is a signed shr, and if all bits shifted in are about to be
7489 // truncated off, turn it into an unsigned shr to allow greater
7490 // simplifications.
7491 if (DestBitSize < SrcBitSize &&
7492 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007493 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007494 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7495 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00007496 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007497 }
7498 }
7499 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007500 }
7501 return 0;
7502}
7503
Chris Lattner8a9f5712007-04-11 06:57:46 +00007504Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007505 if (Instruction *Result = commonIntCastTransforms(CI))
7506 return Result;
7507
7508 Value *Src = CI.getOperand(0);
7509 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007510 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7511 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007512
7513 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7514 switch (SrcI->getOpcode()) {
7515 default: break;
7516 case Instruction::LShr:
7517 // We can shrink lshr to something smaller if we know the bits shifted in
7518 // are already zeros.
7519 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007520 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007521
7522 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007523 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007524 Value* SrcIOp0 = SrcI->getOperand(0);
7525 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007526 if (ShAmt >= DestBitWidth) // All zeros.
7527 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7528
7529 // Okay, we can shrink this. Truncate the input, then return a new
7530 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007531 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7532 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7533 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007534 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007535 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007536 } else { // This is a variable shr.
7537
7538 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7539 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7540 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007541 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007542 Value *One = ConstantInt::get(SrcI->getType(), 1);
7543
Reid Spencer832254e2007-02-02 02:16:23 +00007544 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007545 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007546 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007547 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7548 SrcI->getOperand(0),
7549 "tmp"), CI);
7550 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007551 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007552 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007553 }
7554 break;
7555 }
7556 }
7557
7558 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007559}
7560
Evan Chengb98a10e2008-03-24 00:21:34 +00007561/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7562/// in order to eliminate the icmp.
7563Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7564 bool DoXform) {
7565 // If we are just checking for a icmp eq of a single bit and zext'ing it
7566 // to an integer, then shift the bit to the appropriate place and then
7567 // cast to integer to avoid the comparison.
7568 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7569 const APInt &Op1CV = Op1C->getValue();
7570
7571 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7572 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7573 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7574 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7575 if (!DoXform) return ICI;
7576
7577 Value *In = ICI->getOperand(0);
7578 Value *Sh = ConstantInt::get(In->getType(),
7579 In->getType()->getPrimitiveSizeInBits()-1);
7580 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7581 In->getName()+".lobit"),
7582 CI);
7583 if (In->getType() != CI.getType())
7584 In = CastInst::createIntegerCast(In, CI.getType(),
7585 false/*ZExt*/, "tmp", &CI);
7586
7587 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7588 Constant *One = ConstantInt::get(In->getType(), 1);
7589 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7590 In->getName()+".not"),
7591 CI);
7592 }
7593
7594 return ReplaceInstUsesWith(CI, In);
7595 }
7596
7597
7598
7599 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7600 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7601 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7602 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7603 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7604 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7605 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7606 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7607 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7608 // This only works for EQ and NE
7609 ICI->isEquality()) {
7610 // If Op1C some other power of two, convert:
7611 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7612 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7613 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7614 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7615
7616 APInt KnownZeroMask(~KnownZero);
7617 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7618 if (!DoXform) return ICI;
7619
7620 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7621 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7622 // (X&4) == 2 --> false
7623 // (X&4) != 2 --> true
7624 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7625 Res = ConstantExpr::getZExt(Res, CI.getType());
7626 return ReplaceInstUsesWith(CI, Res);
7627 }
7628
7629 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7630 Value *In = ICI->getOperand(0);
7631 if (ShiftAmt) {
7632 // Perform a logical shr by shiftamt.
7633 // Insert the shift to put the result in the low bit.
7634 In = InsertNewInstBefore(BinaryOperator::createLShr(In,
7635 ConstantInt::get(In->getType(), ShiftAmt),
7636 In->getName()+".lobit"), CI);
7637 }
7638
7639 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7640 Constant *One = ConstantInt::get(In->getType(), 1);
7641 In = BinaryOperator::createXor(In, One, "tmp");
7642 InsertNewInstBefore(cast<Instruction>(In), CI);
7643 }
7644
7645 if (CI.getType() == In->getType())
7646 return ReplaceInstUsesWith(CI, In);
7647 else
7648 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7649 }
7650 }
7651 }
7652
7653 return 0;
7654}
7655
Chris Lattner8a9f5712007-04-11 06:57:46 +00007656Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007657 // If one of the common conversion will work ..
7658 if (Instruction *Result = commonIntCastTransforms(CI))
7659 return Result;
7660
7661 Value *Src = CI.getOperand(0);
7662
7663 // If this is a cast of a cast
7664 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007665 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7666 // types and if the sizes are just right we can convert this into a logical
7667 // 'and' which will be much cheaper than the pair of casts.
7668 if (isa<TruncInst>(CSrc)) {
7669 // Get the sizes of the types involved
7670 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007671 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7672 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7673 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007674 // If we're actually extending zero bits and the trunc is a no-op
7675 if (MidSize < DstSize && SrcSize == DstSize) {
7676 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007677 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007678 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007679 Instruction *And =
7680 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7681 // Unfortunately, if the type changed, we need to cast it back.
7682 if (And->getType() != CI.getType()) {
7683 And->setName(CSrc->getName()+".mask");
7684 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007685 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007686 }
7687 return And;
7688 }
7689 }
7690 }
7691
Evan Chengb98a10e2008-03-24 00:21:34 +00007692 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7693 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007694
Evan Chengb98a10e2008-03-24 00:21:34 +00007695 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7696 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7697 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7698 // of the (zext icmp) will be transformed.
7699 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7700 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7701 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7702 (transformZExtICmp(LHS, CI, false) ||
7703 transformZExtICmp(RHS, CI, false))) {
7704 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7705 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7706 return BinaryOperator::create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007707 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007708 }
7709
Reid Spencer3da59db2006-11-27 01:05:10 +00007710 return 0;
7711}
7712
Chris Lattner8a9f5712007-04-11 06:57:46 +00007713Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007714 if (Instruction *I = commonIntCastTransforms(CI))
7715 return I;
7716
Chris Lattner8a9f5712007-04-11 06:57:46 +00007717 Value *Src = CI.getOperand(0);
7718
7719 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7720 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7721 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7722 // If we are just checking for a icmp eq of a single bit and zext'ing it
7723 // to an integer, then shift the bit to the appropriate place and then
7724 // cast to integer to avoid the comparison.
7725 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7726 const APInt &Op1CV = Op1C->getValue();
7727
7728 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7729 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7730 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7731 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7732 Value *In = ICI->getOperand(0);
7733 Value *Sh = ConstantInt::get(In->getType(),
7734 In->getType()->getPrimitiveSizeInBits()-1);
7735 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007736 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007737 CI);
7738 if (In->getType() != CI.getType())
7739 In = CastInst::createIntegerCast(In, CI.getType(),
7740 true/*SExt*/, "tmp", &CI);
7741
7742 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7743 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7744 In->getName()+".not"), CI);
7745
7746 return ReplaceInstUsesWith(CI, In);
7747 }
7748 }
7749 }
7750
Chris Lattnerba417832007-04-11 06:12:58 +00007751 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007752}
7753
Chris Lattnerb7530652008-01-27 05:29:54 +00007754/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7755/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007756static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007757 APFloat F = CFP->getValueAPF();
7758 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007759 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007760 return 0;
7761}
7762
7763/// LookThroughFPExtensions - If this is an fp extension instruction, look
7764/// through it until we get the source value.
7765static Value *LookThroughFPExtensions(Value *V) {
7766 if (Instruction *I = dyn_cast<Instruction>(V))
7767 if (I->getOpcode() == Instruction::FPExt)
7768 return LookThroughFPExtensions(I->getOperand(0));
7769
7770 // If this value is a constant, return the constant in the smallest FP type
7771 // that can accurately represent it. This allows us to turn
7772 // (float)((double)X+2.0) into x+2.0f.
7773 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7774 if (CFP->getType() == Type::PPC_FP128Ty)
7775 return V; // No constant folding of this.
7776 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007777 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007778 return V;
7779 if (CFP->getType() == Type::DoubleTy)
7780 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007781 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007782 return V;
7783 // Don't try to shrink to various long double types.
7784 }
7785
7786 return V;
7787}
7788
7789Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7790 if (Instruction *I = commonCastTransforms(CI))
7791 return I;
7792
7793 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7794 // smaller than the destination type, we can eliminate the truncate by doing
7795 // the add as the smaller type. This applies to add/sub/mul/div as well as
7796 // many builtins (sqrt, etc).
7797 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7798 if (OpI && OpI->hasOneUse()) {
7799 switch (OpI->getOpcode()) {
7800 default: break;
7801 case Instruction::Add:
7802 case Instruction::Sub:
7803 case Instruction::Mul:
7804 case Instruction::FDiv:
7805 case Instruction::FRem:
7806 const Type *SrcTy = OpI->getType();
7807 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7808 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7809 if (LHSTrunc->getType() != SrcTy &&
7810 RHSTrunc->getType() != SrcTy) {
7811 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7812 // If the source types were both smaller than the destination type of
7813 // the cast, do this xform.
7814 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7815 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7816 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7817 CI.getType(), CI);
7818 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7819 CI.getType(), CI);
7820 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7821 }
7822 }
7823 break;
7824 }
7825 }
7826 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007827}
7828
7829Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7830 return commonCastTransforms(CI);
7831}
7832
7833Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007834 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007835}
7836
7837Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007838 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007839}
7840
7841Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7842 return commonCastTransforms(CI);
7843}
7844
7845Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7846 return commonCastTransforms(CI);
7847}
7848
7849Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007850 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007851}
7852
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007853Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7854 if (Instruction *I = commonCastTransforms(CI))
7855 return I;
7856
7857 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7858 if (!DestPointee->isSized()) return 0;
7859
7860 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7861 ConstantInt *Cst;
7862 Value *X;
7863 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7864 m_ConstantInt(Cst)))) {
7865 // If the source and destination operands have the same type, see if this
7866 // is a single-index GEP.
7867 if (X->getType() == CI.getType()) {
7868 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007869 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007870
7871 // Convert the constant to intptr type.
7872 APInt Offset = Cst->getValue();
7873 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7874
7875 // If Offset is evenly divisible by Size, we can do this xform.
7876 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7877 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007878 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007879 }
7880 }
7881 // TODO: Could handle other cases, e.g. where add is indexing into field of
7882 // struct etc.
7883 } else if (CI.getOperand(0)->hasOneUse() &&
7884 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7885 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7886 // "inttoptr+GEP" instead of "add+intptr".
7887
7888 // Get the size of the pointee type.
7889 uint64_t Size = TD->getABITypeSize(DestPointee);
7890
7891 // Convert the constant to intptr type.
7892 APInt Offset = Cst->getValue();
7893 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7894
7895 // If Offset is evenly divisible by Size, we can do this xform.
7896 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7897 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7898
7899 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7900 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007901 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007902 }
7903 }
7904 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007905}
7906
Chris Lattnerd3e28342007-04-27 17:44:50 +00007907Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007908 // If the operands are integer typed then apply the integer transforms,
7909 // otherwise just apply the common ones.
7910 Value *Src = CI.getOperand(0);
7911 const Type *SrcTy = Src->getType();
7912 const Type *DestTy = CI.getType();
7913
Chris Lattner42a75512007-01-15 02:27:26 +00007914 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007915 if (Instruction *Result = commonIntCastTransforms(CI))
7916 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007917 } else if (isa<PointerType>(SrcTy)) {
7918 if (Instruction *I = commonPointerCastTransforms(CI))
7919 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007920 } else {
7921 if (Instruction *Result = commonCastTransforms(CI))
7922 return Result;
7923 }
7924
7925
7926 // Get rid of casts from one type to the same type. These are useless and can
7927 // be replaced by the operand.
7928 if (DestTy == Src->getType())
7929 return ReplaceInstUsesWith(CI, Src);
7930
Reid Spencer3da59db2006-11-27 01:05:10 +00007931 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007932 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7933 const Type *DstElTy = DstPTy->getElementType();
7934 const Type *SrcElTy = SrcPTy->getElementType();
7935
Nate Begeman83ad90a2008-03-31 00:22:16 +00007936 // If the address spaces don't match, don't eliminate the bitcast, which is
7937 // required for changing types.
7938 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7939 return 0;
7940
Chris Lattnerd3e28342007-04-27 17:44:50 +00007941 // If we are casting a malloc or alloca to a pointer to a type of the same
7942 // size, rewrite the allocation instruction to allocate the "right" type.
7943 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7944 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7945 return V;
7946
Chris Lattnerd717c182007-05-05 22:32:24 +00007947 // If the source and destination are pointers, and this cast is equivalent
7948 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007949 // This can enhance SROA and other transforms that want type-safe pointers.
7950 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7951 unsigned NumZeros = 0;
7952 while (SrcElTy != DstElTy &&
7953 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7954 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7955 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7956 ++NumZeros;
7957 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007958
Chris Lattnerd3e28342007-04-27 17:44:50 +00007959 // If we found a path from the src to dest, create the getelementptr now.
7960 if (SrcElTy == DstElTy) {
7961 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007962 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7963 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007964 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007965 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007966
Reid Spencer3da59db2006-11-27 01:05:10 +00007967 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7968 if (SVI->hasOneUse()) {
7969 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7970 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007971 if (isa<VectorType>(DestTy) &&
7972 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007973 SVI->getType()->getNumElements()) {
7974 CastInst *Tmp;
7975 // If either of the operands is a cast from CI.getType(), then
7976 // evaluating the shuffle in the casted destination's type will allow
7977 // us to eliminate at least one cast.
7978 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7979 Tmp->getOperand(0)->getType() == DestTy) ||
7980 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7981 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007982 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7983 SVI->getOperand(0), DestTy, &CI);
7984 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7985 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007986 // Return a new shuffle vector. Use the same element ID's, as we
7987 // know the vector types match #elts.
7988 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007989 }
7990 }
7991 }
7992 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007993 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007994}
7995
Chris Lattnere576b912004-04-09 23:46:01 +00007996/// GetSelectFoldableOperands - We want to turn code that looks like this:
7997/// %C = or %A, %B
7998/// %D = select %cond, %C, %A
7999/// into:
8000/// %C = select %cond, %B, 0
8001/// %D = or %A, %C
8002///
8003/// Assuming that the specified instruction is an operand to the select, return
8004/// a bitmask indicating which operands of this instruction are foldable if they
8005/// equal the other incoming value of the select.
8006///
8007static unsigned GetSelectFoldableOperands(Instruction *I) {
8008 switch (I->getOpcode()) {
8009 case Instruction::Add:
8010 case Instruction::Mul:
8011 case Instruction::And:
8012 case Instruction::Or:
8013 case Instruction::Xor:
8014 return 3; // Can fold through either operand.
8015 case Instruction::Sub: // Can only fold on the amount subtracted.
8016 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008017 case Instruction::LShr:
8018 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008019 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008020 default:
8021 return 0; // Cannot fold
8022 }
8023}
8024
8025/// GetSelectFoldableConstant - For the same transformation as the previous
8026/// function, return the identity constant that goes into the select.
8027static Constant *GetSelectFoldableConstant(Instruction *I) {
8028 switch (I->getOpcode()) {
8029 default: assert(0 && "This cannot happen!"); abort();
8030 case Instruction::Add:
8031 case Instruction::Sub:
8032 case Instruction::Or:
8033 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008034 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008035 case Instruction::LShr:
8036 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008037 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008038 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008039 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008040 case Instruction::Mul:
8041 return ConstantInt::get(I->getType(), 1);
8042 }
8043}
8044
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008045/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8046/// have the same opcode and only one use each. Try to simplify this.
8047Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8048 Instruction *FI) {
8049 if (TI->getNumOperands() == 1) {
8050 // If this is a non-volatile load or a cast from the same type,
8051 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008052 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008053 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8054 return 0;
8055 } else {
8056 return 0; // unknown unary op.
8057 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008058
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008059 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008060 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8061 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008062 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008063 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
8064 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008065 }
8066
Reid Spencer832254e2007-02-02 02:16:23 +00008067 // Only handle binary operators here.
8068 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008069 return 0;
8070
8071 // Figure out if the operations have any operands in common.
8072 Value *MatchOp, *OtherOpT, *OtherOpF;
8073 bool MatchIsOpZero;
8074 if (TI->getOperand(0) == FI->getOperand(0)) {
8075 MatchOp = TI->getOperand(0);
8076 OtherOpT = TI->getOperand(1);
8077 OtherOpF = FI->getOperand(1);
8078 MatchIsOpZero = true;
8079 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8080 MatchOp = TI->getOperand(1);
8081 OtherOpT = TI->getOperand(0);
8082 OtherOpF = FI->getOperand(0);
8083 MatchIsOpZero = false;
8084 } else if (!TI->isCommutative()) {
8085 return 0;
8086 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8087 MatchOp = TI->getOperand(0);
8088 OtherOpT = TI->getOperand(1);
8089 OtherOpF = FI->getOperand(0);
8090 MatchIsOpZero = true;
8091 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8092 MatchOp = TI->getOperand(1);
8093 OtherOpT = TI->getOperand(0);
8094 OtherOpF = FI->getOperand(1);
8095 MatchIsOpZero = true;
8096 } else {
8097 return 0;
8098 }
8099
8100 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008101 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8102 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008103 InsertNewInstBefore(NewSI, SI);
8104
8105 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8106 if (MatchIsOpZero)
8107 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
8108 else
8109 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008110 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008111 assert(0 && "Shouldn't get here");
8112 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008113}
8114
Chris Lattner3d69f462004-03-12 05:52:32 +00008115Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008116 Value *CondVal = SI.getCondition();
8117 Value *TrueVal = SI.getTrueValue();
8118 Value *FalseVal = SI.getFalseValue();
8119
8120 // select true, X, Y -> X
8121 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008122 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008123 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008124
8125 // select C, X, X -> X
8126 if (TrueVal == FalseVal)
8127 return ReplaceInstUsesWith(SI, TrueVal);
8128
Chris Lattnere87597f2004-10-16 18:11:37 +00008129 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8130 return ReplaceInstUsesWith(SI, FalseVal);
8131 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8132 return ReplaceInstUsesWith(SI, TrueVal);
8133 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8134 if (isa<Constant>(TrueVal))
8135 return ReplaceInstUsesWith(SI, TrueVal);
8136 else
8137 return ReplaceInstUsesWith(SI, FalseVal);
8138 }
8139
Reid Spencer4fe16d62007-01-11 18:21:29 +00008140 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008141 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008142 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008143 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00008144 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008145 } else {
8146 // Change: A = select B, false, C --> A = and !B, C
8147 Value *NotCond =
8148 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
8149 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00008150 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008151 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008152 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008153 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008154 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00008155 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008156 } else {
8157 // Change: A = select B, C, true --> A = or !B, C
8158 Value *NotCond =
8159 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
8160 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00008161 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008162 }
8163 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008164
8165 // select a, b, a -> a&b
8166 // select a, a, b -> a|b
8167 if (CondVal == TrueVal)
8168 return BinaryOperator::createOr(CondVal, FalseVal);
8169 else if (CondVal == FalseVal)
8170 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008171 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008172
Chris Lattner2eefe512004-04-09 19:05:30 +00008173 // Selecting between two integer constants?
8174 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8175 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008176 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008177 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008178 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008179 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008180 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008181 Value *NotCond =
8182 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008183 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008184 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008185 }
Chris Lattnerba417832007-04-11 06:12:58 +00008186
8187 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008188
Reid Spencere4d87aa2006-12-23 06:05:41 +00008189 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008190
Reid Spencere4d87aa2006-12-23 06:05:41 +00008191 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008192 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008193 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008194 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008195 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008196 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008197 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008198 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008199 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8200 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
8201 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008202 InsertNewInstBefore(SRA, SI);
8203
Reid Spencer3da59db2006-11-27 01:05:10 +00008204 // Finally, convert to the type of the select RHS. We figure out
8205 // if this requires a SExt, Trunc or BitCast based on the sizes.
8206 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008207 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8208 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008209 if (SRASize < SISize)
8210 opc = Instruction::SExt;
8211 else if (SRASize > SISize)
8212 opc = Instruction::Trunc;
8213 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008214 }
8215 }
8216
8217
8218 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008219 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008220 // non-constant value, eliminate this whole mess. This corresponds to
8221 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008222 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008223 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008224 cast<Constant>(IC->getOperand(1))->isNullValue())
8225 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8226 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008227 isa<ConstantInt>(ICA->getOperand(1)) &&
8228 (ICA->getOperand(1) == TrueValC ||
8229 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008230 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8231 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008232 // know whether we have a icmp_ne or icmp_eq and whether the
8233 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008234 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008235 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008236 Value *V = ICA;
8237 if (ShouldNotVal)
8238 V = InsertNewInstBefore(BinaryOperator::create(
8239 Instruction::Xor, V, ICA->getOperand(1)), SI);
8240 return ReplaceInstUsesWith(SI, V);
8241 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008242 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008243 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008244
8245 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008246 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8247 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008248 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008249 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8250 // This is not safe in general for floating point:
8251 // consider X== -0, Y== +0.
8252 // It becomes safe if either operand is a nonzero constant.
8253 ConstantFP *CFPt, *CFPf;
8254 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8255 !CFPt->getValueAPF().isZero()) ||
8256 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8257 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008258 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008259 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008260 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008261 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008262 return ReplaceInstUsesWith(SI, TrueVal);
8263 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8264
Reid Spencere4d87aa2006-12-23 06:05:41 +00008265 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008266 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008267 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8268 // This is not safe in general for floating point:
8269 // consider X== -0, Y== +0.
8270 // It becomes safe if either operand is a nonzero constant.
8271 ConstantFP *CFPt, *CFPf;
8272 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8273 !CFPt->getValueAPF().isZero()) ||
8274 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8275 !CFPf->getValueAPF().isZero()))
8276 return ReplaceInstUsesWith(SI, FalseVal);
8277 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008278 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008279 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8280 return ReplaceInstUsesWith(SI, TrueVal);
8281 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8282 }
8283 }
8284
8285 // See if we are selecting two values based on a comparison of the two values.
8286 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8287 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8288 // Transform (X == Y) ? X : Y -> Y
8289 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8290 return ReplaceInstUsesWith(SI, FalseVal);
8291 // Transform (X != Y) ? X : Y -> X
8292 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8293 return ReplaceInstUsesWith(SI, TrueVal);
8294 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8295
8296 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8297 // Transform (X == Y) ? Y : X -> X
8298 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8299 return ReplaceInstUsesWith(SI, FalseVal);
8300 // Transform (X != Y) ? Y : X -> Y
8301 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008302 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008303 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8304 }
8305 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008306
Chris Lattner87875da2005-01-13 22:52:24 +00008307 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8308 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8309 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008310 Instruction *AddOp = 0, *SubOp = 0;
8311
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008312 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8313 if (TI->getOpcode() == FI->getOpcode())
8314 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8315 return IV;
8316
8317 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8318 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008319 if (TI->getOpcode() == Instruction::Sub &&
8320 FI->getOpcode() == Instruction::Add) {
8321 AddOp = FI; SubOp = TI;
8322 } else if (FI->getOpcode() == Instruction::Sub &&
8323 TI->getOpcode() == Instruction::Add) {
8324 AddOp = TI; SubOp = FI;
8325 }
8326
8327 if (AddOp) {
8328 Value *OtherAddOp = 0;
8329 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8330 OtherAddOp = AddOp->getOperand(1);
8331 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8332 OtherAddOp = AddOp->getOperand(0);
8333 }
8334
8335 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008336 // So at this point we know we have (Y -> OtherAddOp):
8337 // select C, (add X, Y), (sub X, Z)
8338 Value *NegVal; // Compute -Z
8339 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8340 NegVal = ConstantExpr::getNeg(C);
8341 } else {
8342 NegVal = InsertNewInstBefore(
8343 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008344 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008345
8346 Value *NewTrueOp = OtherAddOp;
8347 Value *NewFalseOp = NegVal;
8348 if (AddOp != TI)
8349 std::swap(NewTrueOp, NewFalseOp);
8350 Instruction *NewSel =
Gabor Greif051a9502008-04-06 20:25:17 +00008351 SelectInst::Create(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008352
8353 NewSel = InsertNewInstBefore(NewSel, SI);
8354 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008355 }
8356 }
8357 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008358
Chris Lattnere576b912004-04-09 23:46:01 +00008359 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008360 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008361 // See the comment above GetSelectFoldableOperands for a description of the
8362 // transformation we are doing here.
8363 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8364 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8365 !isa<Constant>(FalseVal))
8366 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8367 unsigned OpToFold = 0;
8368 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8369 OpToFold = 1;
8370 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8371 OpToFold = 2;
8372 }
8373
8374 if (OpToFold) {
8375 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008376 Instruction *NewSel =
Gabor Greif051a9502008-04-06 20:25:17 +00008377 SelectInst::Create(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008378 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008379 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008380 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8381 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008382 else {
8383 assert(0 && "Unknown instruction!!");
8384 }
8385 }
8386 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008387
Chris Lattnere576b912004-04-09 23:46:01 +00008388 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8389 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8390 !isa<Constant>(TrueVal))
8391 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8392 unsigned OpToFold = 0;
8393 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8394 OpToFold = 1;
8395 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8396 OpToFold = 2;
8397 }
8398
8399 if (OpToFold) {
8400 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008401 Instruction *NewSel =
Gabor Greif051a9502008-04-06 20:25:17 +00008402 SelectInst::Create(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008403 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008404 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008405 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8406 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008407 else
Chris Lattnere576b912004-04-09 23:46:01 +00008408 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008409 }
8410 }
8411 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008412
8413 if (BinaryOperator::isNot(CondVal)) {
8414 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8415 SI.setOperand(1, FalseVal);
8416 SI.setOperand(2, TrueVal);
8417 return &SI;
8418 }
8419
Chris Lattner3d69f462004-03-12 05:52:32 +00008420 return 0;
8421}
8422
Dan Gohmaneee962e2008-04-10 18:43:06 +00008423/// EnforceKnownAlignment - If the specified pointer points to an object that
8424/// we control, modify the object's alignment to PrefAlign. This isn't
8425/// often possible though. If alignment is important, a more reliable approach
8426/// is to simply align all global variables and allocation instructions to
8427/// their preferred alignment from the beginning.
8428///
8429static unsigned EnforceKnownAlignment(Value *V,
8430 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008431
Dan Gohmaneee962e2008-04-10 18:43:06 +00008432 User *U = dyn_cast<User>(V);
8433 if (!U) return Align;
8434
8435 switch (getOpcode(U)) {
8436 default: break;
8437 case Instruction::BitCast:
8438 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8439 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008440 // If all indexes are zero, it is just the alignment of the base pointer.
8441 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008442 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8443 if (!isa<Constant>(U->getOperand(i)) ||
8444 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008445 AllZeroOperands = false;
8446 break;
8447 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008448
8449 if (AllZeroOperands) {
8450 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008451 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008452 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008453 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008454 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008455 }
8456
8457 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8458 // If there is a large requested alignment and we can, bump up the alignment
8459 // of the global.
8460 if (!GV->isDeclaration()) {
8461 GV->setAlignment(PrefAlign);
8462 Align = PrefAlign;
8463 }
8464 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8465 // If there is a requested alignment and if this is an alloca, round up. We
8466 // don't do this for malloc, because some systems can't respect the request.
8467 if (isa<AllocaInst>(AI)) {
8468 AI->setAlignment(PrefAlign);
8469 Align = PrefAlign;
8470 }
8471 }
8472
8473 return Align;
8474}
8475
8476/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8477/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8478/// and it is more than the alignment of the ultimate object, see if we can
8479/// increase the alignment of the ultimate object, making this check succeed.
8480unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8481 unsigned PrefAlign) {
8482 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8483 sizeof(PrefAlign) * CHAR_BIT;
8484 APInt Mask = APInt::getAllOnesValue(BitWidth);
8485 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8486 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8487 unsigned TrailZ = KnownZero.countTrailingOnes();
8488 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8489
8490 if (PrefAlign > Align)
8491 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8492
8493 // We don't need to make any adjustment.
8494 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008495}
8496
Chris Lattnerf497b022008-01-13 23:50:23 +00008497Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008498 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8499 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008500 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8501 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8502
8503 if (CopyAlign < MinAlign) {
8504 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8505 return MI;
8506 }
8507
8508 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8509 // load/store.
8510 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8511 if (MemOpLength == 0) return 0;
8512
Chris Lattner37ac6082008-01-14 00:28:35 +00008513 // Source and destination pointer types are always "i8*" for intrinsic. See
8514 // if the size is something we can handle with a single primitive load/store.
8515 // A single load+store correctly handles overlapping memory in the memmove
8516 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008517 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008518 if (Size == 0) return MI; // Delete this mem transfer.
8519
8520 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008521 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008522
Chris Lattner37ac6082008-01-14 00:28:35 +00008523 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008524 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008525
8526 // Memcpy forces the use of i8* for the source and destination. That means
8527 // that if you're using memcpy to move one double around, you'll get a cast
8528 // from double* to i8*. We'd much rather use a double load+store rather than
8529 // an i64 load+store, here because this improves the odds that the source or
8530 // dest address will be promotable. See if we can find a better type than the
8531 // integer datatype.
8532 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8533 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8534 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8535 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8536 // down through these levels if so.
8537 while (!SrcETy->isFirstClassType()) {
8538 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8539 if (STy->getNumElements() == 1)
8540 SrcETy = STy->getElementType(0);
8541 else
8542 break;
8543 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8544 if (ATy->getNumElements() == 1)
8545 SrcETy = ATy->getElementType();
8546 else
8547 break;
8548 } else
8549 break;
8550 }
8551
8552 if (SrcETy->isFirstClassType())
8553 NewPtrTy = PointerType::getUnqual(SrcETy);
8554 }
8555 }
8556
8557
Chris Lattnerf497b022008-01-13 23:50:23 +00008558 // If the memcpy/memmove provides better alignment info than we can
8559 // infer, use it.
8560 SrcAlign = std::max(SrcAlign, CopyAlign);
8561 DstAlign = std::max(DstAlign, CopyAlign);
8562
8563 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8564 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008565 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8566 InsertNewInstBefore(L, *MI);
8567 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8568
8569 // Set the size of the copy to 0, it will be deleted on the next iteration.
8570 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8571 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008572}
Chris Lattner3d69f462004-03-12 05:52:32 +00008573
Chris Lattner69ea9d22008-04-30 06:39:11 +00008574Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8575 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8576 if (MI->getAlignment()->getZExtValue() < Alignment) {
8577 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8578 return MI;
8579 }
8580
8581 // Extract the length and alignment and fill if they are constant.
8582 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8583 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8584 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8585 return 0;
8586 uint64_t Len = LenC->getZExtValue();
8587 Alignment = MI->getAlignment()->getZExtValue();
8588
8589 // If the length is zero, this is a no-op
8590 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8591
8592 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8593 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8594 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8595
8596 Value *Dest = MI->getDest();
8597 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8598
8599 // Alignment 0 is identity for alignment 1 for memset, but not store.
8600 if (Alignment == 0) Alignment = 1;
8601
8602 // Extract the fill value and store.
8603 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8604 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8605 Alignment), *MI);
8606
8607 // Set the size of the copy to 0, it will be deleted on the next iteration.
8608 MI->setLength(Constant::getNullValue(LenC->getType()));
8609 return MI;
8610 }
8611
8612 return 0;
8613}
8614
8615
Chris Lattner8b0ea312006-01-13 20:11:04 +00008616/// visitCallInst - CallInst simplification. This mostly only handles folding
8617/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8618/// the heavy lifting.
8619///
Chris Lattner9fe38862003-06-19 17:00:31 +00008620Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008621 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8622 if (!II) return visitCallSite(&CI);
8623
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008624 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8625 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008626 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008627 bool Changed = false;
8628
8629 // memmove/cpy/set of zero bytes is a noop.
8630 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8631 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8632
Chris Lattner35b9e482004-10-12 04:52:52 +00008633 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008634 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008635 // Replace the instruction with just byte operations. We would
8636 // transform other cases to loads/stores, but we don't know if
8637 // alignment is sufficient.
8638 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008639 }
8640
Chris Lattner35b9e482004-10-12 04:52:52 +00008641 // If we have a memmove and the source operation is a constant global,
8642 // then the source and dest pointers can't alias, so we can change this
8643 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008644 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008645 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8646 if (GVSrc->isConstant()) {
8647 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008648 Intrinsic::ID MemCpyID;
8649 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8650 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008651 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008652 MemCpyID = Intrinsic::memcpy_i64;
8653 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008654 Changed = true;
8655 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008656 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008657
Chris Lattner95a959d2006-03-06 20:18:44 +00008658 // If we can determine a pointer alignment that is bigger than currently
8659 // set, update the alignment.
8660 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008661 if (Instruction *I = SimplifyMemTransfer(MI))
8662 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008663 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8664 if (Instruction *I = SimplifyMemSet(MSI))
8665 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008666 }
8667
Chris Lattner8b0ea312006-01-13 20:11:04 +00008668 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008669 } else {
8670 switch (II->getIntrinsicID()) {
8671 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008672 case Intrinsic::ppc_altivec_lvx:
8673 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008674 case Intrinsic::x86_sse_loadu_ps:
8675 case Intrinsic::x86_sse2_loadu_pd:
8676 case Intrinsic::x86_sse2_loadu_dq:
8677 // Turn PPC lvx -> load if the pointer is known aligned.
8678 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008679 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008680 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8681 PointerType::getUnqual(II->getType()),
8682 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008683 return new LoadInst(Ptr);
8684 }
8685 break;
8686 case Intrinsic::ppc_altivec_stvx:
8687 case Intrinsic::ppc_altivec_stvxl:
8688 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008689 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008690 const Type *OpPtrTy =
8691 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008692 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008693 return new StoreInst(II->getOperand(1), Ptr);
8694 }
8695 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008696 case Intrinsic::x86_sse_storeu_ps:
8697 case Intrinsic::x86_sse2_storeu_pd:
8698 case Intrinsic::x86_sse2_storeu_dq:
8699 case Intrinsic::x86_sse2_storel_dq:
8700 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008701 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008702 const Type *OpPtrTy =
8703 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008704 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008705 return new StoreInst(II->getOperand(2), Ptr);
8706 }
8707 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008708
8709 case Intrinsic::x86_sse_cvttss2si: {
8710 // These intrinsics only demands the 0th element of its input vector. If
8711 // we can simplify the input based on that, do so now.
8712 uint64_t UndefElts;
8713 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8714 UndefElts)) {
8715 II->setOperand(1, V);
8716 return II;
8717 }
8718 break;
8719 }
8720
Chris Lattnere2ed0572006-04-06 19:19:17 +00008721 case Intrinsic::ppc_altivec_vperm:
8722 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008723 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008724 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8725
8726 // Check that all of the elements are integer constants or undefs.
8727 bool AllEltsOk = true;
8728 for (unsigned i = 0; i != 16; ++i) {
8729 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8730 !isa<UndefValue>(Mask->getOperand(i))) {
8731 AllEltsOk = false;
8732 break;
8733 }
8734 }
8735
8736 if (AllEltsOk) {
8737 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008738 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8739 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008740 Value *Result = UndefValue::get(Op0->getType());
8741
8742 // Only extract each element once.
8743 Value *ExtractedElts[32];
8744 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8745
8746 for (unsigned i = 0; i != 16; ++i) {
8747 if (isa<UndefValue>(Mask->getOperand(i)))
8748 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008749 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008750 Idx &= 31; // Match the hardware behavior.
8751
8752 if (ExtractedElts[Idx] == 0) {
8753 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008754 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008755 InsertNewInstBefore(Elt, CI);
8756 ExtractedElts[Idx] = Elt;
8757 }
8758
8759 // Insert this value into the result vector.
Gabor Greif051a9502008-04-06 20:25:17 +00008760 Result = InsertElementInst::Create(Result, ExtractedElts[Idx], i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008761 InsertNewInstBefore(cast<Instruction>(Result), CI);
8762 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008763 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008764 }
8765 }
8766 break;
8767
Chris Lattnera728ddc2006-01-13 21:28:09 +00008768 case Intrinsic::stackrestore: {
8769 // If the save is right next to the restore, remove the restore. This can
8770 // happen when variable allocas are DCE'd.
8771 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8772 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8773 BasicBlock::iterator BI = SS;
8774 if (&*++BI == II)
8775 return EraseInstFromFunction(CI);
8776 }
8777 }
8778
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008779 // Scan down this block to see if there is another stack restore in the
8780 // same block without an intervening call/alloca.
8781 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008782 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008783 bool CannotRemove = false;
8784 for (++BI; &*BI != TI; ++BI) {
8785 if (isa<AllocaInst>(BI)) {
8786 CannotRemove = true;
8787 break;
8788 }
8789 if (isa<CallInst>(BI)) {
8790 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008791 CannotRemove = true;
8792 break;
8793 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008794 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008795 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008796 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008797 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008798
8799 // If the stack restore is in a return/unwind block and if there are no
8800 // allocas or calls between the restore and the return, nuke the restore.
8801 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8802 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008803 break;
8804 }
8805 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008806 }
8807
Chris Lattner8b0ea312006-01-13 20:11:04 +00008808 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008809}
8810
8811// InvokeInst simplification
8812//
8813Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008814 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008815}
8816
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008817/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8818/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008819static bool isSafeToEliminateVarargsCast(const CallSite CS,
8820 const CastInst * const CI,
8821 const TargetData * const TD,
8822 const int ix) {
8823 if (!CI->isLosslessCast())
8824 return false;
8825
8826 // The size of ByVal arguments is derived from the type, so we
8827 // can't change to a type with a different size. If the size were
8828 // passed explicitly we could avoid this check.
8829 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8830 return true;
8831
8832 const Type* SrcTy =
8833 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8834 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8835 if (!SrcTy->isSized() || !DstTy->isSized())
8836 return false;
8837 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8838 return false;
8839 return true;
8840}
8841
Chris Lattnera44d8a22003-10-07 22:32:43 +00008842// visitCallSite - Improvements for call and invoke instructions.
8843//
8844Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008845 bool Changed = false;
8846
8847 // If the callee is a constexpr cast of a function, attempt to move the cast
8848 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008849 if (transformConstExprCastCall(CS)) return 0;
8850
Chris Lattner6c266db2003-10-07 22:54:13 +00008851 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008852
Chris Lattner08b22ec2005-05-13 07:09:09 +00008853 if (Function *CalleeF = dyn_cast<Function>(Callee))
8854 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8855 Instruction *OldCall = CS.getInstruction();
8856 // If the call and callee calling conventions don't match, this call must
8857 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008858 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008859 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8860 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008861 if (!OldCall->use_empty())
8862 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8863 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8864 return EraseInstFromFunction(*OldCall);
8865 return 0;
8866 }
8867
Chris Lattner17be6352004-10-18 02:59:09 +00008868 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8869 // This instruction is not reachable, just remove it. We insert a store to
8870 // undef so that we know that this code is not reachable, despite the fact
8871 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008872 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008873 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008874 CS.getInstruction());
8875
8876 if (!CS.getInstruction()->use_empty())
8877 CS.getInstruction()->
8878 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8879
8880 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8881 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008882 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8883 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008884 }
Chris Lattner17be6352004-10-18 02:59:09 +00008885 return EraseInstFromFunction(*CS.getInstruction());
8886 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008887
Duncan Sandscdb6d922007-09-17 10:26:40 +00008888 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8889 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8890 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8891 return transformCallThroughTrampoline(CS);
8892
Chris Lattner6c266db2003-10-07 22:54:13 +00008893 const PointerType *PTy = cast<PointerType>(Callee->getType());
8894 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8895 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00008896 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00008897 // See if we can optimize any arguments passed through the varargs area of
8898 // the call.
8899 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00008900 E = CS.arg_end(); I != E; ++I, ++ix) {
8901 CastInst *CI = dyn_cast<CastInst>(*I);
8902 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8903 *I = CI->getOperand(0);
8904 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00008905 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00008906 }
Chris Lattner6c266db2003-10-07 22:54:13 +00008907 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008908
Duncan Sandsf0c33542007-12-19 21:13:37 +00008909 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008910 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008911 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008912 Changed = true;
8913 }
8914
Chris Lattner6c266db2003-10-07 22:54:13 +00008915 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008916}
8917
Chris Lattner9fe38862003-06-19 17:00:31 +00008918// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8919// attempt to move the cast to the arguments of the call/invoke.
8920//
8921bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8922 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8923 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008924 if (CE->getOpcode() != Instruction::BitCast ||
8925 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008926 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008927 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008928 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008929 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008930
8931 // Okay, this is a cast from a function to a different type. Unless doing so
8932 // would cause a type conversion of one of our arguments, change this call to
8933 // be a direct call with arguments casted to the appropriate types.
8934 //
8935 const FunctionType *FT = Callee->getFunctionType();
8936 const Type *OldRetTy = Caller->getType();
8937
Devang Patel75e6f022008-03-11 18:04:06 +00008938 if (isa<StructType>(FT->getReturnType()))
8939 return false; // TODO: Handle multiple return values.
8940
Chris Lattnerf78616b2004-01-14 06:06:08 +00008941 // Check to see if we are changing the return type...
8942 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008943 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008944 // Conversion is ok if changing from pointer to int of same size.
8945 !(isa<PointerType>(FT->getReturnType()) &&
8946 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008947 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008948
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008949 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008950 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008951 FT->getReturnType() != Type::VoidTy &&
8952 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008953 return false; // Cannot transform this return value.
8954
Chris Lattner58d74912008-03-12 17:45:29 +00008955 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8956 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008957 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8958 return false; // Attribute not compatible with transformed value.
8959 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008960
Chris Lattnerf78616b2004-01-14 06:06:08 +00008961 // If the callsite is an invoke instruction, and the return value is used by
8962 // a PHI node in a successor, we cannot change the return type of the call
8963 // because there is no place to put the cast instruction (without breaking
8964 // the critical edge). Bail out in this case.
8965 if (!Caller->use_empty())
8966 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8967 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8968 UI != E; ++UI)
8969 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8970 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008971 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008972 return false;
8973 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008974
8975 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8976 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008977
Chris Lattner9fe38862003-06-19 17:00:31 +00008978 CallSite::arg_iterator AI = CS.arg_begin();
8979 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8980 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008981 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008982
8983 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008984 return false; // Cannot transform this parameter value.
8985
Chris Lattner58d74912008-03-12 17:45:29 +00008986 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8987 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008988
Reid Spencer3da59db2006-11-27 01:05:10 +00008989 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008990 // Some conversions are safe even if we do not have a body.
8991 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008992 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008993 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008994 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008995 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8996 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008997 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008998 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008999 }
9000
9001 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009002 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009003 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009004
Chris Lattner58d74912008-03-12 17:45:29 +00009005 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9006 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009007 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009008 // won't be dropping them. Check that these extra arguments have attributes
9009 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009010 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9011 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009012 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009013 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009014 if (PAttrs & ParamAttr::VarArgsIncompatible)
9015 return false;
9016 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009017
Chris Lattner9fe38862003-06-19 17:00:31 +00009018 // Okay, we decided that this is a safe thing to do: go ahead and start
9019 // inserting cast instructions as necessary...
9020 std::vector<Value*> Args;
9021 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009022 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009023 attrVec.reserve(NumCommonArgs);
9024
9025 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009026 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009027
9028 // If the return value is not being used, the type may not be compatible
9029 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009030 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009031
9032 // Add the new return attributes.
9033 if (RAttrs)
9034 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009035
9036 AI = CS.arg_begin();
9037 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9038 const Type *ParamTy = FT->getParamType(i);
9039 if ((*AI)->getType() == ParamTy) {
9040 Args.push_back(*AI);
9041 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009042 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009043 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00009044 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009045 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009046 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009047
9048 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009049 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009050 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009051 }
9052
9053 // If the function takes more arguments than the call was taking, add them
9054 // now...
9055 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9056 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9057
9058 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009059 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009060 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009061 cerr << "WARNING: While resolving call to function '"
9062 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009063 } else {
9064 // Add all of the arguments in their promoted form to the arg list...
9065 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9066 const Type *PTy = getPromotedType((*AI)->getType());
9067 if (PTy != (*AI)->getType()) {
9068 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009069 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9070 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00009071 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009072 InsertNewInstBefore(Cast, *Caller);
9073 Args.push_back(Cast);
9074 } else {
9075 Args.push_back(*AI);
9076 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009077
Duncan Sandse1e520f2008-01-13 08:02:44 +00009078 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009079 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009080 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9081 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009082 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009083 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009084
9085 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009086 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009087
Chris Lattner58d74912008-03-12 17:45:29 +00009088 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009089
Chris Lattner9fe38862003-06-19 17:00:31 +00009090 Instruction *NC;
9091 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009092 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9093 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009094 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009095 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009096 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009097 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9098 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009099 CallInst *CI = cast<CallInst>(Caller);
9100 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009101 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009102 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009103 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009104 }
9105
Chris Lattner6934a042007-02-11 01:23:03 +00009106 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009107 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009108 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009109 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009110 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009111 OldRetTy, false);
9112 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009113
9114 // If this is an invoke instruction, we should insert it after the first
9115 // non-phi, instruction in the normal successor block.
9116 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9117 BasicBlock::iterator I = II->getNormalDest()->begin();
9118 while (isa<PHINode>(I)) ++I;
9119 InsertNewInstBefore(NC, *I);
9120 } else {
9121 // Otherwise, it's a call, just insert cast right after the call instr
9122 InsertNewInstBefore(NC, *Caller);
9123 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009124 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009125 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009126 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009127 }
9128 }
9129
9130 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9131 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009132 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009133 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009134 return true;
9135}
9136
Duncan Sandscdb6d922007-09-17 10:26:40 +00009137// transformCallThroughTrampoline - Turn a call to a function created by the
9138// init_trampoline intrinsic into a direct call to the underlying function.
9139//
9140Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9141 Value *Callee = CS.getCalledValue();
9142 const PointerType *PTy = cast<PointerType>(Callee->getType());
9143 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009144 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009145
9146 // If the call already has the 'nest' attribute somewhere then give up -
9147 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009148 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009149 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009150
9151 IntrinsicInst *Tramp =
9152 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9153
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009154 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009155 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9156 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9157
Chris Lattner58d74912008-03-12 17:45:29 +00009158 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9159 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009160 unsigned NestIdx = 1;
9161 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009162 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009163
9164 // Look for a parameter marked with the 'nest' attribute.
9165 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9166 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009167 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009168 // Record the parameter type and any other attributes.
9169 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009170 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009171 break;
9172 }
9173
9174 if (NestTy) {
9175 Instruction *Caller = CS.getInstruction();
9176 std::vector<Value*> NewArgs;
9177 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9178
Chris Lattner58d74912008-03-12 17:45:29 +00009179 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9180 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009181
Duncan Sandscdb6d922007-09-17 10:26:40 +00009182 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009183 // mean appending it. Likewise for attributes.
9184
9185 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009186 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9187 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009188
Duncan Sandscdb6d922007-09-17 10:26:40 +00009189 {
9190 unsigned Idx = 1;
9191 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9192 do {
9193 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009194 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009195 Value *NestVal = Tramp->getOperand(3);
9196 if (NestVal->getType() != NestTy)
9197 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9198 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009199 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009200 }
9201
9202 if (I == E)
9203 break;
9204
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009205 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009206 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009207 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009208 NewAttrs.push_back
9209 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009210
9211 ++Idx, ++I;
9212 } while (1);
9213 }
9214
9215 // The trampoline may have been bitcast to a bogus type (FTy).
9216 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009217 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009218
Duncan Sandscdb6d922007-09-17 10:26:40 +00009219 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009220 NewTypes.reserve(FTy->getNumParams()+1);
9221
Duncan Sandscdb6d922007-09-17 10:26:40 +00009222 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009223 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009224 {
9225 unsigned Idx = 1;
9226 FunctionType::param_iterator I = FTy->param_begin(),
9227 E = FTy->param_end();
9228
9229 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009230 if (Idx == NestIdx)
9231 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009232 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009233
9234 if (I == E)
9235 break;
9236
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009237 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009238 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009239
9240 ++Idx, ++I;
9241 } while (1);
9242 }
9243
9244 // Replace the trampoline call with a direct call. Let the generic
9245 // code sort out any function type mismatches.
9246 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009247 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009248 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9249 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009250 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009251
9252 Instruction *NewCaller;
9253 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009254 NewCaller = InvokeInst::Create(NewCallee,
9255 II->getNormalDest(), II->getUnwindDest(),
9256 NewArgs.begin(), NewArgs.end(),
9257 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009258 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009259 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009260 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009261 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9262 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009263 if (cast<CallInst>(Caller)->isTailCall())
9264 cast<CallInst>(NewCaller)->setTailCall();
9265 cast<CallInst>(NewCaller)->
9266 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009267 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009268 }
9269 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9270 Caller->replaceAllUsesWith(NewCaller);
9271 Caller->eraseFromParent();
9272 RemoveFromWorkList(Caller);
9273 return 0;
9274 }
9275 }
9276
9277 // Replace the trampoline call with a direct call. Since there is no 'nest'
9278 // parameter, there is no need to adjust the argument list. Let the generic
9279 // code sort out any function type mismatches.
9280 Constant *NewCallee =
9281 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9282 CS.setCalledFunction(NewCallee);
9283 return CS.getInstruction();
9284}
9285
Chris Lattner7da52b22006-11-01 04:51:18 +00009286/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9287/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9288/// and a single binop.
9289Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9290 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009291 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9292 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009293 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009294 Value *LHSVal = FirstInst->getOperand(0);
9295 Value *RHSVal = FirstInst->getOperand(1);
9296
9297 const Type *LHSType = LHSVal->getType();
9298 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009299
9300 // Scan to see if all operands are the same opcode, all have one use, and all
9301 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009302 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009303 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009304 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009305 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009306 // types or GEP's with different index types.
9307 I->getOperand(0)->getType() != LHSType ||
9308 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009309 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009310
9311 // If they are CmpInst instructions, check their predicates
9312 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9313 if (cast<CmpInst>(I)->getPredicate() !=
9314 cast<CmpInst>(FirstInst)->getPredicate())
9315 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009316
9317 // Keep track of which operand needs a phi node.
9318 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9319 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009320 }
9321
Chris Lattner53738a42006-11-08 19:42:28 +00009322 // Otherwise, this is safe to transform, determine if it is profitable.
9323
9324 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9325 // Indexes are often folded into load/store instructions, so we don't want to
9326 // hide them behind a phi.
9327 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9328 return 0;
9329
Chris Lattner7da52b22006-11-01 04:51:18 +00009330 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009331 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009332 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009333 if (LHSVal == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00009334 NewLHS = PHINode::Create(LHSType, FirstInst->getOperand(0)->getName()+".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009335 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9336 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009337 InsertNewInstBefore(NewLHS, PN);
9338 LHSVal = NewLHS;
9339 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009340
9341 if (RHSVal == 0) {
Gabor Greif051a9502008-04-06 20:25:17 +00009342 NewRHS = PHINode::Create(RHSType, FirstInst->getOperand(1)->getName()+".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009343 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9344 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009345 InsertNewInstBefore(NewRHS, PN);
9346 RHSVal = NewRHS;
9347 }
9348
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009349 // Add all operands to the new PHIs.
9350 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9351 if (NewLHS) {
9352 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9353 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9354 }
9355 if (NewRHS) {
9356 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9357 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9358 }
9359 }
9360
Chris Lattner7da52b22006-11-01 04:51:18 +00009361 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00009362 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009363 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9364 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
9365 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009366 else {
9367 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009368 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009369 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009370}
9371
Chris Lattner76c73142006-11-01 07:13:54 +00009372/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9373/// of the block that defines it. This means that it must be obvious the value
9374/// of the load is not changed from the point of the load to the end of the
9375/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009376///
9377/// Finally, it is safe, but not profitable, to sink a load targetting a
9378/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9379/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009380static bool isSafeToSinkLoad(LoadInst *L) {
9381 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9382
9383 for (++BBI; BBI != E; ++BBI)
9384 if (BBI->mayWriteToMemory())
9385 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009386
9387 // Check for non-address taken alloca. If not address-taken already, it isn't
9388 // profitable to do this xform.
9389 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9390 bool isAddressTaken = false;
9391 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9392 UI != E; ++UI) {
9393 if (isa<LoadInst>(UI)) continue;
9394 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9395 // If storing TO the alloca, then the address isn't taken.
9396 if (SI->getOperand(1) == AI) continue;
9397 }
9398 isAddressTaken = true;
9399 break;
9400 }
9401
9402 if (!isAddressTaken)
9403 return false;
9404 }
9405
Chris Lattner76c73142006-11-01 07:13:54 +00009406 return true;
9407}
9408
Chris Lattner9fe38862003-06-19 17:00:31 +00009409
Chris Lattnerbac32862004-11-14 19:13:23 +00009410// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9411// operator and they all are only used by the PHI, PHI together their
9412// inputs, and do the operation once, to the result of the PHI.
9413Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9414 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9415
9416 // Scan the instruction, looking for input operations that can be folded away.
9417 // If all input operands to the phi are the same instruction (e.g. a cast from
9418 // the same type or "+42") we can pull the operation through the PHI, reducing
9419 // code size and simplifying code.
9420 Constant *ConstantOp = 0;
9421 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009422 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009423 if (isa<CastInst>(FirstInst)) {
9424 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009425 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009426 // Can fold binop, compare or shift here if the RHS is a constant,
9427 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009428 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009429 if (ConstantOp == 0)
9430 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009431 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9432 isVolatile = LI->isVolatile();
9433 // We can't sink the load if the loaded value could be modified between the
9434 // load and the PHI.
9435 if (LI->getParent() != PN.getIncomingBlock(0) ||
9436 !isSafeToSinkLoad(LI))
9437 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009438 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009439 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009440 return FoldPHIArgBinOpIntoPHI(PN);
9441 // Can't handle general GEPs yet.
9442 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009443 } else {
9444 return 0; // Cannot fold this operation.
9445 }
9446
9447 // Check to see if all arguments are the same operation.
9448 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9449 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9450 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009451 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009452 return 0;
9453 if (CastSrcTy) {
9454 if (I->getOperand(0)->getType() != CastSrcTy)
9455 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009456 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009457 // We can't sink the load if the loaded value could be modified between
9458 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009459 if (LI->isVolatile() != isVolatile ||
9460 LI->getParent() != PN.getIncomingBlock(i) ||
9461 !isSafeToSinkLoad(LI))
9462 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009463
9464 // If the PHI is volatile and its block has multiple successors, sinking
9465 // it would remove a load of the volatile value from the path through the
9466 // other successor.
9467 if (isVolatile &&
9468 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9469 return 0;
9470
9471
Chris Lattnerbac32862004-11-14 19:13:23 +00009472 } else if (I->getOperand(1) != ConstantOp) {
9473 return 0;
9474 }
9475 }
9476
9477 // Okay, they are all the same operation. Create a new PHI node of the
9478 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009479 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9480 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009481 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009482
9483 Value *InVal = FirstInst->getOperand(0);
9484 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009485
9486 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009487 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9488 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9489 if (NewInVal != InVal)
9490 InVal = 0;
9491 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9492 }
9493
9494 Value *PhiVal;
9495 if (InVal) {
9496 // The new PHI unions all of the same values together. This is really
9497 // common, so we handle it intelligently here for compile-time speed.
9498 PhiVal = InVal;
9499 delete NewPN;
9500 } else {
9501 InsertNewInstBefore(NewPN, PN);
9502 PhiVal = NewPN;
9503 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009504
Chris Lattnerbac32862004-11-14 19:13:23 +00009505 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009506 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9507 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009508 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00009509 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009510 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Reid Spencere4d87aa2006-12-23 06:05:41 +00009511 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
9512 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009513 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9514
9515 // If this was a volatile load that we are merging, make sure to loop through
9516 // and mark all the input loads as non-volatile. If we don't do this, we will
9517 // insert a new volatile load and the old ones will not be deletable.
9518 if (isVolatile)
9519 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9520 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9521
9522 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009523}
Chris Lattnera1be5662002-05-02 17:06:02 +00009524
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009525/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9526/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009527static bool DeadPHICycle(PHINode *PN,
9528 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009529 if (PN->use_empty()) return true;
9530 if (!PN->hasOneUse()) return false;
9531
9532 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009533 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009534 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009535
9536 // Don't scan crazily complex things.
9537 if (PotentiallyDeadPHIs.size() == 16)
9538 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009539
9540 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9541 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009542
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009543 return false;
9544}
9545
Chris Lattnercf5008a2007-11-06 21:52:06 +00009546/// PHIsEqualValue - Return true if this phi node is always equal to
9547/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9548/// z = some value; x = phi (y, z); y = phi (x, z)
9549static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9550 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9551 // See if we already saw this PHI node.
9552 if (!ValueEqualPHIs.insert(PN))
9553 return true;
9554
9555 // Don't scan crazily complex things.
9556 if (ValueEqualPHIs.size() == 16)
9557 return false;
9558
9559 // Scan the operands to see if they are either phi nodes or are equal to
9560 // the value.
9561 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9562 Value *Op = PN->getIncomingValue(i);
9563 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9564 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9565 return false;
9566 } else if (Op != NonPhiInVal)
9567 return false;
9568 }
9569
9570 return true;
9571}
9572
9573
Chris Lattner473945d2002-05-06 18:06:38 +00009574// PHINode simplification
9575//
Chris Lattner7e708292002-06-25 16:13:24 +00009576Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009577 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009578 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009579
Owen Anderson7e057142006-07-10 22:03:18 +00009580 if (Value *V = PN.hasConstantValue())
9581 return ReplaceInstUsesWith(PN, V);
9582
Owen Anderson7e057142006-07-10 22:03:18 +00009583 // If all PHI operands are the same operation, pull them through the PHI,
9584 // reducing code size.
9585 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9586 PN.getIncomingValue(0)->hasOneUse())
9587 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9588 return Result;
9589
9590 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9591 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9592 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009593 if (PN.hasOneUse()) {
9594 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9595 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009596 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009597 PotentiallyDeadPHIs.insert(&PN);
9598 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9599 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9600 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009601
9602 // If this phi has a single use, and if that use just computes a value for
9603 // the next iteration of a loop, delete the phi. This occurs with unused
9604 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9605 // common case here is good because the only other things that catch this
9606 // are induction variable analysis (sometimes) and ADCE, which is only run
9607 // late.
9608 if (PHIUser->hasOneUse() &&
9609 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9610 PHIUser->use_back() == &PN) {
9611 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9612 }
9613 }
Owen Anderson7e057142006-07-10 22:03:18 +00009614
Chris Lattnercf5008a2007-11-06 21:52:06 +00009615 // We sometimes end up with phi cycles that non-obviously end up being the
9616 // same value, for example:
9617 // z = some value; x = phi (y, z); y = phi (x, z)
9618 // where the phi nodes don't necessarily need to be in the same block. Do a
9619 // quick check to see if the PHI node only contains a single non-phi value, if
9620 // so, scan to see if the phi cycle is actually equal to that value.
9621 {
9622 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9623 // Scan for the first non-phi operand.
9624 while (InValNo != NumOperandVals &&
9625 isa<PHINode>(PN.getIncomingValue(InValNo)))
9626 ++InValNo;
9627
9628 if (InValNo != NumOperandVals) {
9629 Value *NonPhiInVal = PN.getOperand(InValNo);
9630
9631 // Scan the rest of the operands to see if there are any conflicts, if so
9632 // there is no need to recursively scan other phis.
9633 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9634 Value *OpVal = PN.getIncomingValue(InValNo);
9635 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9636 break;
9637 }
9638
9639 // If we scanned over all operands, then we have one unique value plus
9640 // phi values. Scan PHI nodes to see if they all merge in each other or
9641 // the value.
9642 if (InValNo == NumOperandVals) {
9643 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9644 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9645 return ReplaceInstUsesWith(PN, NonPhiInVal);
9646 }
9647 }
9648 }
Chris Lattner60921c92003-12-19 05:58:40 +00009649 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009650}
9651
Reid Spencer17212df2006-12-12 09:18:51 +00009652static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9653 Instruction *InsertPoint,
9654 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009655 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9656 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009657 // We must cast correctly to the pointer type. Ensure that we
9658 // sign extend the integer value if it is smaller as this is
9659 // used for address computation.
9660 Instruction::CastOps opcode =
9661 (VTySize < PtrSize ? Instruction::SExt :
9662 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9663 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009664}
9665
Chris Lattnera1be5662002-05-02 17:06:02 +00009666
Chris Lattner7e708292002-06-25 16:13:24 +00009667Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009668 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009669 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009670 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009671 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009672 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009673
Chris Lattnere87597f2004-10-16 18:11:37 +00009674 if (isa<UndefValue>(GEP.getOperand(0)))
9675 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9676
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009677 bool HasZeroPointerIndex = false;
9678 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9679 HasZeroPointerIndex = C->isNullValue();
9680
9681 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009682 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009683
Chris Lattner28977af2004-04-05 01:30:19 +00009684 // Eliminate unneeded casts for indices.
9685 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009686
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009687 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009688 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009689 if (isa<SequentialType>(*GTI)) {
9690 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009691 if (CI->getOpcode() == Instruction::ZExt ||
9692 CI->getOpcode() == Instruction::SExt) {
9693 const Type *SrcTy = CI->getOperand(0)->getType();
9694 // We can eliminate a cast from i32 to i64 iff the target
9695 // is a 32-bit pointer target.
9696 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9697 MadeChange = true;
9698 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009699 }
9700 }
9701 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009702 // If we are using a wider index than needed for this platform, shrink it
9703 // to what we need. If the incoming value needs a cast instruction,
9704 // insert it. This explicit cast can make subsequent optimizations more
9705 // obvious.
9706 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009707 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009708 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009709 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009710 MadeChange = true;
9711 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009712 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9713 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009714 GEP.setOperand(i, Op);
9715 MadeChange = true;
9716 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009717 }
Chris Lattner28977af2004-04-05 01:30:19 +00009718 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009719 }
Chris Lattner28977af2004-04-05 01:30:19 +00009720 if (MadeChange) return &GEP;
9721
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009722 // If this GEP instruction doesn't move the pointer, and if the input operand
9723 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9724 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009725 if (GEP.hasAllZeroIndices()) {
9726 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9727 // If the bitcast is of an allocation, and the allocation will be
9728 // converted to match the type of the cast, don't touch this.
9729 if (isa<AllocationInst>(BCI->getOperand(0))) {
9730 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009731 if (Instruction *I = visitBitCast(*BCI)) {
9732 if (I != BCI) {
9733 I->takeName(BCI);
9734 BCI->getParent()->getInstList().insert(BCI, I);
9735 ReplaceInstUsesWith(*BCI, I);
9736 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009737 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009738 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009739 }
9740 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9741 }
9742 }
9743
Chris Lattner90ac28c2002-08-02 19:29:35 +00009744 // Combine Indices - If the source pointer to this getelementptr instruction
9745 // is a getelementptr instruction, combine the indices of the two
9746 // getelementptr instructions into a single instruction.
9747 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009748 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009749 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009750 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009751
9752 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009753 // Note that if our source is a gep chain itself that we wait for that
9754 // chain to be resolved before we perform this transformation. This
9755 // avoids us creating a TON of code in some cases.
9756 //
9757 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9758 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9759 return 0; // Wait until our source is folded to completion.
9760
Chris Lattner72588fc2007-02-15 22:48:32 +00009761 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009762
9763 // Find out whether the last index in the source GEP is a sequential idx.
9764 bool EndsWithSequential = false;
9765 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9766 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009767 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009768
Chris Lattner90ac28c2002-08-02 19:29:35 +00009769 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009770 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009771 // Replace: gep (gep %P, long B), long A, ...
9772 // With: T = long A+B; gep %P, T, ...
9773 //
Chris Lattner620ce142004-05-07 22:09:22 +00009774 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009775 if (SO1 == Constant::getNullValue(SO1->getType())) {
9776 Sum = GO1;
9777 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9778 Sum = SO1;
9779 } else {
9780 // If they aren't the same type, convert both to an integer of the
9781 // target's pointer size.
9782 if (SO1->getType() != GO1->getType()) {
9783 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009784 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009785 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009786 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009787 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009788 unsigned PS = TD->getPointerSizeInBits();
9789 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009790 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009791 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009792
Duncan Sands514ab342007-11-01 20:53:16 +00009793 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009794 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009795 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009796 } else {
9797 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009798 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9799 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009800 }
9801 }
9802 }
Chris Lattner620ce142004-05-07 22:09:22 +00009803 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9804 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9805 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009806 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9807 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009808 }
Chris Lattner28977af2004-04-05 01:30:19 +00009809 }
Chris Lattner620ce142004-05-07 22:09:22 +00009810
9811 // Recycle the GEP we already have if possible.
9812 if (SrcGEPOperands.size() == 2) {
9813 GEP.setOperand(0, SrcGEPOperands[0]);
9814 GEP.setOperand(1, Sum);
9815 return &GEP;
9816 } else {
9817 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9818 SrcGEPOperands.end()-1);
9819 Indices.push_back(Sum);
9820 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9821 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009822 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009823 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009824 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009825 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009826 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9827 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009828 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9829 }
9830
9831 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009832 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9833 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009834
Chris Lattner620ce142004-05-07 22:09:22 +00009835 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009836 // GEP of global variable. If all of the indices for this GEP are
9837 // constants, we can promote this to a constexpr instead of an instruction.
9838
9839 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009840 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009841 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9842 for (; I != E && isa<Constant>(*I); ++I)
9843 Indices.push_back(cast<Constant>(*I));
9844
9845 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009846 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9847 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009848
9849 // Replace all uses of the GEP with the new constexpr...
9850 return ReplaceInstUsesWith(GEP, CE);
9851 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009852 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009853 if (!isa<PointerType>(X->getType())) {
9854 // Not interesting. Source pointer must be a cast from pointer.
9855 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009856 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9857 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009858 //
9859 // This occurs when the program declares an array extern like "int X[];"
9860 //
9861 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9862 const PointerType *XTy = cast<PointerType>(X->getType());
9863 if (const ArrayType *XATy =
9864 dyn_cast<ArrayType>(XTy->getElementType()))
9865 if (const ArrayType *CATy =
9866 dyn_cast<ArrayType>(CPTy->getElementType()))
9867 if (CATy->getElementType() == XATy->getElementType()) {
9868 // At this point, we know that the cast source type is a pointer
9869 // to an array of the same type as the destination pointer
9870 // array. Because the array type is never stepped over (there
9871 // is a leading zero) we can fold the cast into this GEP.
9872 GEP.setOperand(0, X);
9873 return &GEP;
9874 }
9875 } else if (GEP.getNumOperands() == 2) {
9876 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009877 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9878 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009879 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9880 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9881 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009882 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9883 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009884 Value *Idx[2];
9885 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9886 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009887 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009888 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009889 // V and GEP are both pointer types --> BitCast
9890 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009891 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009892
9893 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009894 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009895 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009896 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009897
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009898 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009899 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009900 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009901
9902 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9903 // allow either a mul, shift, or constant here.
9904 Value *NewIdx = 0;
9905 ConstantInt *Scale = 0;
9906 if (ArrayEltSize == 1) {
9907 NewIdx = GEP.getOperand(1);
9908 Scale = ConstantInt::get(NewIdx->getType(), 1);
9909 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009910 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009911 Scale = CI;
9912 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9913 if (Inst->getOpcode() == Instruction::Shl &&
9914 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009915 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9916 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9917 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009918 NewIdx = Inst->getOperand(0);
9919 } else if (Inst->getOpcode() == Instruction::Mul &&
9920 isa<ConstantInt>(Inst->getOperand(1))) {
9921 Scale = cast<ConstantInt>(Inst->getOperand(1));
9922 NewIdx = Inst->getOperand(0);
9923 }
9924 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009925
Chris Lattner7835cdd2005-09-13 18:36:04 +00009926 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009927 // out, perform the transformation. Note, we don't know whether Scale is
9928 // signed or not. We'll use unsigned version of division/modulo
9929 // operation after making sure Scale doesn't have the sign bit set.
9930 if (Scale && Scale->getSExtValue() >= 0LL &&
9931 Scale->getZExtValue() % ArrayEltSize == 0) {
9932 Scale = ConstantInt::get(Scale->getType(),
9933 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009934 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009935 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009936 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009937 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9938 NewIdx = InsertNewInstBefore(Sc, GEP);
9939 }
9940
9941 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009942 Value *Idx[2];
9943 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9944 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009945 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009946 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009947 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9948 // The NewGEP must be pointer typed, so must the old one -> BitCast
9949 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009950 }
9951 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009952 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009953 }
9954
Chris Lattner8a2a3112001-12-14 16:52:21 +00009955 return 0;
9956}
9957
Chris Lattner0864acf2002-11-04 16:18:53 +00009958Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9959 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009960 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009961 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9962 const Type *NewTy =
9963 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009964 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009965
9966 // Create and insert the replacement instruction...
9967 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009968 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009969 else {
9970 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009971 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009972 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009973
9974 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009975
Chris Lattner0864acf2002-11-04 16:18:53 +00009976 // Scan to the end of the allocation instructions, to skip over a block of
9977 // allocas if possible...
9978 //
9979 BasicBlock::iterator It = New;
9980 while (isa<AllocationInst>(*It)) ++It;
9981
9982 // Now that I is pointing to the first non-allocation-inst in the block,
9983 // insert our getelementptr instruction...
9984 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009985 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009986 Value *Idx[2];
9987 Idx[0] = NullIdx;
9988 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +00009989 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9990 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009991
9992 // Now make everything use the getelementptr instead of the original
9993 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009994 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009995 } else if (isa<UndefValue>(AI.getArraySize())) {
9996 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009997 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009998 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009999
10000 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10001 // Note that we only do this for alloca's, because malloc should allocate and
10002 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010003 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010004 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010005 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10006
Chris Lattner0864acf2002-11-04 16:18:53 +000010007 return 0;
10008}
10009
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010010Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10011 Value *Op = FI.getOperand(0);
10012
Chris Lattner17be6352004-10-18 02:59:09 +000010013 // free undef -> unreachable.
10014 if (isa<UndefValue>(Op)) {
10015 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010016 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010017 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010018 return EraseInstFromFunction(FI);
10019 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010020
Chris Lattner6160e852004-02-28 04:57:37 +000010021 // If we have 'free null' delete the instruction. This can happen in stl code
10022 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010023 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010024 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010025
10026 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10027 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10028 FI.setOperand(0, CI->getOperand(0));
10029 return &FI;
10030 }
10031
10032 // Change free (gep X, 0,0,0,0) into free(X)
10033 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10034 if (GEPI->hasAllZeroIndices()) {
10035 AddToWorkList(GEPI);
10036 FI.setOperand(0, GEPI->getOperand(0));
10037 return &FI;
10038 }
10039 }
10040
10041 // Change free(malloc) into nothing, if the malloc has a single use.
10042 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10043 if (MI->hasOneUse()) {
10044 EraseInstFromFunction(FI);
10045 return EraseInstFromFunction(*MI);
10046 }
Chris Lattner6160e852004-02-28 04:57:37 +000010047
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010048 return 0;
10049}
10050
10051
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010052/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010053static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010054 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010055 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010056 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010057
Devang Patel99db6ad2007-10-18 19:52:32 +000010058 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10059 // Instead of loading constant c string, use corresponding integer value
10060 // directly if string length is small enough.
10061 const std::string &Str = CE->getOperand(0)->getStringValue();
10062 if (!Str.empty()) {
10063 unsigned len = Str.length();
10064 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10065 unsigned numBits = Ty->getPrimitiveSizeInBits();
10066 // Replace LI with immediate integer store.
10067 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010068 APInt StrVal(numBits, 0);
10069 APInt SingleChar(numBits, 0);
10070 if (TD->isLittleEndian()) {
10071 for (signed i = len-1; i >= 0; i--) {
10072 SingleChar = (uint64_t) Str[i];
10073 StrVal = (StrVal << 8) | SingleChar;
10074 }
10075 } else {
10076 for (unsigned i = 0; i < len; i++) {
10077 SingleChar = (uint64_t) Str[i];
10078 StrVal = (StrVal << 8) | SingleChar;
10079 }
10080 // Append NULL at the end.
10081 SingleChar = 0;
10082 StrVal = (StrVal << 8) | SingleChar;
10083 }
10084 Value *NL = ConstantInt::get(StrVal);
10085 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010086 }
10087 }
10088 }
10089
Chris Lattnerb89e0712004-07-13 01:49:43 +000010090 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010091 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010092 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010093
Reid Spencer42230162007-01-22 05:51:25 +000010094 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010095 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010096 // If the source is an array, the code below will not succeed. Check to
10097 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10098 // constants.
10099 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10100 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10101 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010102 Value *Idxs[2];
10103 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10104 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010105 SrcTy = cast<PointerType>(CastOp->getType());
10106 SrcPTy = SrcTy->getElementType();
10107 }
10108
Reid Spencer42230162007-01-22 05:51:25 +000010109 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010110 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010111 // Do not allow turning this into a load of an integer, which is then
10112 // casted to a pointer, this pessimizes pointer analysis a lot.
10113 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010114 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10115 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010116
Chris Lattnerf9527852005-01-31 04:50:46 +000010117 // Okay, we are casting from one integer or pointer type to another of
10118 // the same size. Instead of casting the pointer before the load, cast
10119 // the result of the loaded value.
10120 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10121 CI->getName(),
10122 LI.isVolatile()),LI);
10123 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010124 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010125 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010126 }
10127 }
10128 return 0;
10129}
10130
Chris Lattnerc10aced2004-09-19 18:43:46 +000010131/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010132/// from this value cannot trap. If it is not obviously safe to load from the
10133/// specified pointer, we do a quick local scan of the basic block containing
10134/// ScanFrom, to determine if the address is already accessed.
10135static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010136 // If it is an alloca it is always safe to load from.
10137 if (isa<AllocaInst>(V)) return true;
10138
Duncan Sands46318cd2007-09-19 10:25:38 +000010139 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010140 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010141 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010142 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010143
10144 // Otherwise, be a little bit agressive by scanning the local block where we
10145 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010146 // from/to. If so, the previous load or store would have already trapped,
10147 // so there is no harm doing an extra load (also, CSE will later eliminate
10148 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010149 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10150
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010151 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010152 --BBI;
10153
10154 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10155 if (LI->getOperand(0) == V) return true;
10156 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10157 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010158
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010159 }
Chris Lattner8a375202004-09-19 19:18:10 +000010160 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010161}
10162
Chris Lattner8d2e8882007-08-11 18:48:48 +000010163/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10164/// until we find the underlying object a pointer is referring to or something
10165/// we don't understand. Note that the returned pointer may be offset from the
10166/// input, because we ignore GEP indices.
10167static Value *GetUnderlyingObject(Value *Ptr) {
10168 while (1) {
10169 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10170 if (CE->getOpcode() == Instruction::BitCast ||
10171 CE->getOpcode() == Instruction::GetElementPtr)
10172 Ptr = CE->getOperand(0);
10173 else
10174 return Ptr;
10175 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10176 Ptr = BCI->getOperand(0);
10177 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10178 Ptr = GEP->getOperand(0);
10179 } else {
10180 return Ptr;
10181 }
10182 }
10183}
10184
Chris Lattner833b8a42003-06-26 05:06:25 +000010185Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10186 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010187
Dan Gohman9941f742007-07-20 16:34:21 +000010188 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010189 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10190 if (KnownAlign >
10191 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10192 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010193 LI.setAlignment(KnownAlign);
10194
Chris Lattner37366c12005-05-01 04:24:53 +000010195 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010196 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010197 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010198 return Res;
10199
10200 // None of the following transforms are legal for volatile loads.
10201 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010202
Chris Lattner62f254d2005-09-12 22:00:15 +000010203 if (&LI.getParent()->front() != &LI) {
10204 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010205 // If the instruction immediately before this is a store to the same
10206 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010207 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10208 if (SI->getOperand(1) == LI.getOperand(0))
10209 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010210 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10211 if (LIB->getOperand(0) == LI.getOperand(0))
10212 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010213 }
Chris Lattner37366c12005-05-01 04:24:53 +000010214
Christopher Lambb15147e2007-12-29 07:56:53 +000010215 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10216 const Value *GEPI0 = GEPI->getOperand(0);
10217 // TODO: Consider a target hook for valid address spaces for this xform.
10218 if (isa<ConstantPointerNull>(GEPI0) &&
10219 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010220 // Insert a new store to null instruction before the load to indicate
10221 // that this code is not reachable. We do this instead of inserting
10222 // an unreachable instruction directly because we cannot modify the
10223 // CFG.
10224 new StoreInst(UndefValue::get(LI.getType()),
10225 Constant::getNullValue(Op->getType()), &LI);
10226 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10227 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010228 }
Chris Lattner37366c12005-05-01 04:24:53 +000010229
Chris Lattnere87597f2004-10-16 18:11:37 +000010230 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010231 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010232 // TODO: Consider a target hook for valid address spaces for this xform.
10233 if (isa<UndefValue>(C) || (C->isNullValue() &&
10234 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010235 // Insert a new store to null instruction before the load to indicate that
10236 // this code is not reachable. We do this instead of inserting an
10237 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010238 new StoreInst(UndefValue::get(LI.getType()),
10239 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010240 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010241 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010242
Chris Lattnere87597f2004-10-16 18:11:37 +000010243 // Instcombine load (constant global) into the value loaded.
10244 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010245 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010246 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010247
Chris Lattnere87597f2004-10-16 18:11:37 +000010248 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010249 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010250 if (CE->getOpcode() == Instruction::GetElementPtr) {
10251 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010252 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010253 if (Constant *V =
10254 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010255 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010256 if (CE->getOperand(0)->isNullValue()) {
10257 // Insert a new store to null instruction before the load to indicate
10258 // that this code is not reachable. We do this instead of inserting
10259 // an unreachable instruction directly because we cannot modify the
10260 // CFG.
10261 new StoreInst(UndefValue::get(LI.getType()),
10262 Constant::getNullValue(Op->getType()), &LI);
10263 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10264 }
10265
Reid Spencer3da59db2006-11-27 01:05:10 +000010266 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010267 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010268 return Res;
10269 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010270 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010271 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010272
10273 // If this load comes from anywhere in a constant global, and if the global
10274 // is all undef or zero, we know what it loads.
10275 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10276 if (GV->isConstant() && GV->hasInitializer()) {
10277 if (GV->getInitializer()->isNullValue())
10278 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10279 else if (isa<UndefValue>(GV->getInitializer()))
10280 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10281 }
10282 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010283
Chris Lattner37366c12005-05-01 04:24:53 +000010284 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010285 // Change select and PHI nodes to select values instead of addresses: this
10286 // helps alias analysis out a lot, allows many others simplifications, and
10287 // exposes redundancy in the code.
10288 //
10289 // Note that we cannot do the transformation unless we know that the
10290 // introduced loads cannot trap! Something like this is valid as long as
10291 // the condition is always false: load (select bool %C, int* null, int* %G),
10292 // but it would not be valid if we transformed it to load from null
10293 // unconditionally.
10294 //
10295 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10296 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010297 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10298 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010299 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010300 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010301 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010302 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010303 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010304 }
10305
Chris Lattner684fe212004-09-23 15:46:00 +000010306 // load (select (cond, null, P)) -> load P
10307 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10308 if (C->isNullValue()) {
10309 LI.setOperand(0, SI->getOperand(2));
10310 return &LI;
10311 }
10312
10313 // load (select (cond, P, null)) -> load P
10314 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10315 if (C->isNullValue()) {
10316 LI.setOperand(0, SI->getOperand(1));
10317 return &LI;
10318 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010319 }
10320 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010321 return 0;
10322}
10323
Reid Spencer55af2b52007-01-19 21:20:31 +000010324/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010325/// when possible.
10326static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10327 User *CI = cast<User>(SI.getOperand(1));
10328 Value *CastOp = CI->getOperand(0);
10329
10330 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10331 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10332 const Type *SrcPTy = SrcTy->getElementType();
10333
Reid Spencer42230162007-01-22 05:51:25 +000010334 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010335 // If the source is an array, the code below will not succeed. Check to
10336 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10337 // constants.
10338 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10339 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10340 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010341 Value* Idxs[2];
10342 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10343 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010344 SrcTy = cast<PointerType>(CastOp->getType());
10345 SrcPTy = SrcTy->getElementType();
10346 }
10347
Reid Spencer67f827c2007-01-20 23:35:48 +000010348 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10349 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10350 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010351
10352 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010353 // the same size. Instead of casting the pointer before
10354 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010355 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010356 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010357 Instruction::CastOps opcode = Instruction::BitCast;
10358 const Type* CastSrcTy = SIOp0->getType();
10359 const Type* CastDstTy = SrcPTy;
10360 if (isa<PointerType>(CastDstTy)) {
10361 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010362 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010363 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010364 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010365 opcode = Instruction::PtrToInt;
10366 }
10367 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010368 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010369 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010370 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +000010371 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
10372 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010373 return new StoreInst(NewCast, CastOp);
10374 }
10375 }
10376 }
10377 return 0;
10378}
10379
Chris Lattner2f503e62005-01-31 05:36:43 +000010380Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10381 Value *Val = SI.getOperand(0);
10382 Value *Ptr = SI.getOperand(1);
10383
10384 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010385 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010386 ++NumCombined;
10387 return 0;
10388 }
Chris Lattner836692d2007-01-15 06:51:56 +000010389
10390 // If the RHS is an alloca with a single use, zapify the store, making the
10391 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010392 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010393 if (isa<AllocaInst>(Ptr)) {
10394 EraseInstFromFunction(SI);
10395 ++NumCombined;
10396 return 0;
10397 }
10398
10399 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10400 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10401 GEP->getOperand(0)->hasOneUse()) {
10402 EraseInstFromFunction(SI);
10403 ++NumCombined;
10404 return 0;
10405 }
10406 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010407
Dan Gohman9941f742007-07-20 16:34:21 +000010408 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010409 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10410 if (KnownAlign >
10411 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10412 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010413 SI.setAlignment(KnownAlign);
10414
Chris Lattner9ca96412006-02-08 03:25:32 +000010415 // Do really simple DSE, to catch cases where there are several consequtive
10416 // stores to the same location, separated by a few arithmetic operations. This
10417 // situation often occurs with bitfield accesses.
10418 BasicBlock::iterator BBI = &SI;
10419 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10420 --ScanInsts) {
10421 --BBI;
10422
10423 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10424 // Prev store isn't volatile, and stores to the same location?
10425 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10426 ++NumDeadStore;
10427 ++BBI;
10428 EraseInstFromFunction(*PrevSI);
10429 continue;
10430 }
10431 break;
10432 }
10433
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010434 // If this is a load, we have to stop. However, if the loaded value is from
10435 // the pointer we're loading and is producing the pointer we're storing,
10436 // then *this* store is dead (X = load P; store X -> P).
10437 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010438 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010439 EraseInstFromFunction(SI);
10440 ++NumCombined;
10441 return 0;
10442 }
10443 // Otherwise, this is a load from some other location. Stores before it
10444 // may not be dead.
10445 break;
10446 }
10447
Chris Lattner9ca96412006-02-08 03:25:32 +000010448 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010449 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010450 break;
10451 }
10452
10453
10454 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010455
10456 // store X, null -> turns into 'unreachable' in SimplifyCFG
10457 if (isa<ConstantPointerNull>(Ptr)) {
10458 if (!isa<UndefValue>(Val)) {
10459 SI.setOperand(0, UndefValue::get(Val->getType()));
10460 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010461 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010462 ++NumCombined;
10463 }
10464 return 0; // Do not modify these!
10465 }
10466
10467 // store undef, Ptr -> noop
10468 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010469 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010470 ++NumCombined;
10471 return 0;
10472 }
10473
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010474 // If the pointer destination is a cast, see if we can fold the cast into the
10475 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010476 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010477 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10478 return Res;
10479 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010480 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010481 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10482 return Res;
10483
Chris Lattner408902b2005-09-12 23:23:25 +000010484
10485 // If this store is the last instruction in the basic block, and if the block
10486 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010487 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010488 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010489 if (BI->isUnconditional())
10490 if (SimplifyStoreAtEndOfBlock(SI))
10491 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010492
Chris Lattner2f503e62005-01-31 05:36:43 +000010493 return 0;
10494}
10495
Chris Lattner3284d1f2007-04-15 00:07:55 +000010496/// SimplifyStoreAtEndOfBlock - Turn things like:
10497/// if () { *P = v1; } else { *P = v2 }
10498/// into a phi node with a store in the successor.
10499///
Chris Lattner31755a02007-04-15 01:02:18 +000010500/// Simplify things like:
10501/// *P = v1; if () { *P = v2; }
10502/// into a phi node with a store in the successor.
10503///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010504bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10505 BasicBlock *StoreBB = SI.getParent();
10506
10507 // Check to see if the successor block has exactly two incoming edges. If
10508 // so, see if the other predecessor contains a store to the same location.
10509 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010510 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010511
10512 // Determine whether Dest has exactly two predecessors and, if so, compute
10513 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010514 pred_iterator PI = pred_begin(DestBB);
10515 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010516 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010517 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010518 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010519 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010520 return false;
10521
10522 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010523 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010524 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010525 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010526 }
Chris Lattner31755a02007-04-15 01:02:18 +000010527 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010528 return false;
10529
10530
Chris Lattner31755a02007-04-15 01:02:18 +000010531 // Verify that the other block ends in a branch and is not otherwise empty.
10532 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010533 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010534 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010535 return false;
10536
Chris Lattner31755a02007-04-15 01:02:18 +000010537 // If the other block ends in an unconditional branch, check for the 'if then
10538 // else' case. there is an instruction before the branch.
10539 StoreInst *OtherStore = 0;
10540 if (OtherBr->isUnconditional()) {
10541 // If this isn't a store, or isn't a store to the same location, bail out.
10542 --BBI;
10543 OtherStore = dyn_cast<StoreInst>(BBI);
10544 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10545 return false;
10546 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010547 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010548 // destinations is StoreBB, then we have the if/then case.
10549 if (OtherBr->getSuccessor(0) != StoreBB &&
10550 OtherBr->getSuccessor(1) != StoreBB)
10551 return false;
10552
10553 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010554 // if/then triangle. See if there is a store to the same ptr as SI that
10555 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010556 for (;; --BBI) {
10557 // Check to see if we find the matching store.
10558 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10559 if (OtherStore->getOperand(1) != SI.getOperand(1))
10560 return false;
10561 break;
10562 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010563 // If we find something that may be using the stored value, or if we run
10564 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010565 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10566 BBI == OtherBB->begin())
10567 return false;
10568 }
10569
10570 // In order to eliminate the store in OtherBr, we have to
10571 // make sure nothing reads the stored value in StoreBB.
10572 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10573 // FIXME: This should really be AA driven.
10574 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10575 return false;
10576 }
10577 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010578
Chris Lattner31755a02007-04-15 01:02:18 +000010579 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010580 Value *MergedVal = OtherStore->getOperand(0);
10581 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010582 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010583 PN->reserveOperandSpace(2);
10584 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010585 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10586 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010587 }
10588
10589 // Advance to a place where it is safe to insert the new store and
10590 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010591 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010592 while (isa<PHINode>(BBI)) ++BBI;
10593 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10594 OtherStore->isVolatile()), *BBI);
10595
10596 // Nuke the old stores.
10597 EraseInstFromFunction(SI);
10598 EraseInstFromFunction(*OtherStore);
10599 ++NumCombined;
10600 return true;
10601}
10602
Chris Lattner2f503e62005-01-31 05:36:43 +000010603
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010604Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10605 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010606 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010607 BasicBlock *TrueDest;
10608 BasicBlock *FalseDest;
10609 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10610 !isa<Constant>(X)) {
10611 // Swap Destinations and condition...
10612 BI.setCondition(X);
10613 BI.setSuccessor(0, FalseDest);
10614 BI.setSuccessor(1, TrueDest);
10615 return &BI;
10616 }
10617
Reid Spencere4d87aa2006-12-23 06:05:41 +000010618 // Cannonicalize fcmp_one -> fcmp_oeq
10619 FCmpInst::Predicate FPred; Value *Y;
10620 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10621 TrueDest, FalseDest)))
10622 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10623 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10624 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010625 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010626 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10627 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010628 // Swap Destinations and condition...
10629 BI.setCondition(NewSCC);
10630 BI.setSuccessor(0, FalseDest);
10631 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010632 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010633 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010634 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010635 return &BI;
10636 }
10637
10638 // Cannonicalize icmp_ne -> icmp_eq
10639 ICmpInst::Predicate IPred;
10640 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10641 TrueDest, FalseDest)))
10642 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10643 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10644 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10645 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010646 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010647 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10648 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010649 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010650 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010651 BI.setSuccessor(0, FalseDest);
10652 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010653 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010654 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010655 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010656 return &BI;
10657 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010658
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010659 return 0;
10660}
Chris Lattner0864acf2002-11-04 16:18:53 +000010661
Chris Lattner46238a62004-07-03 00:26:11 +000010662Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10663 Value *Cond = SI.getCondition();
10664 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10665 if (I->getOpcode() == Instruction::Add)
10666 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10667 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10668 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010669 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010670 AddRHS));
10671 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010672 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010673 return &SI;
10674 }
10675 }
10676 return 0;
10677}
10678
Chris Lattner220b0cf2006-03-05 00:22:33 +000010679/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10680/// is to leave as a vector operation.
10681static bool CheapToScalarize(Value *V, bool isConstant) {
10682 if (isa<ConstantAggregateZero>(V))
10683 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010684 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010685 if (isConstant) return true;
10686 // If all elts are the same, we can extract.
10687 Constant *Op0 = C->getOperand(0);
10688 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10689 if (C->getOperand(i) != Op0)
10690 return false;
10691 return true;
10692 }
10693 Instruction *I = dyn_cast<Instruction>(V);
10694 if (!I) return false;
10695
10696 // Insert element gets simplified to the inserted element or is deleted if
10697 // this is constant idx extract element and its a constant idx insertelt.
10698 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10699 isa<ConstantInt>(I->getOperand(2)))
10700 return true;
10701 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10702 return true;
10703 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10704 if (BO->hasOneUse() &&
10705 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10706 CheapToScalarize(BO->getOperand(1), isConstant)))
10707 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010708 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10709 if (CI->hasOneUse() &&
10710 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10711 CheapToScalarize(CI->getOperand(1), isConstant)))
10712 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010713
10714 return false;
10715}
10716
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010717/// Read and decode a shufflevector mask.
10718///
10719/// It turns undef elements into values that are larger than the number of
10720/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010721static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10722 unsigned NElts = SVI->getType()->getNumElements();
10723 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10724 return std::vector<unsigned>(NElts, 0);
10725 if (isa<UndefValue>(SVI->getOperand(2)))
10726 return std::vector<unsigned>(NElts, 2*NElts);
10727
10728 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010729 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010730 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10731 if (isa<UndefValue>(CP->getOperand(i)))
10732 Result.push_back(NElts*2); // undef -> 8
10733 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010734 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010735 return Result;
10736}
10737
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010738/// FindScalarElement - Given a vector and an element number, see if the scalar
10739/// value is already around as a register, for example if it were inserted then
10740/// extracted from the vector.
10741static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010742 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10743 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010744 unsigned Width = PTy->getNumElements();
10745 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010746 return UndefValue::get(PTy->getElementType());
10747
10748 if (isa<UndefValue>(V))
10749 return UndefValue::get(PTy->getElementType());
10750 else if (isa<ConstantAggregateZero>(V))
10751 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010752 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010753 return CP->getOperand(EltNo);
10754 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10755 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010756 if (!isa<ConstantInt>(III->getOperand(2)))
10757 return 0;
10758 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010759
10760 // If this is an insert to the element we are looking for, return the
10761 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010762 if (EltNo == IIElt)
10763 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010764
10765 // Otherwise, the insertelement doesn't modify the value, recurse on its
10766 // vector input.
10767 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010768 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010769 unsigned InEl = getShuffleMask(SVI)[EltNo];
10770 if (InEl < Width)
10771 return FindScalarElement(SVI->getOperand(0), InEl);
10772 else if (InEl < Width*2)
10773 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10774 else
10775 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010776 }
10777
10778 // Otherwise, we don't know.
10779 return 0;
10780}
10781
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010782Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010783
Dan Gohman07a96762007-07-16 14:29:03 +000010784 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010785 if (isa<UndefValue>(EI.getOperand(0)))
10786 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10787
Dan Gohman07a96762007-07-16 14:29:03 +000010788 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010789 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10790 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10791
Reid Spencer9d6565a2007-02-15 02:26:10 +000010792 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010793 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010794 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010795 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010796 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010797 if (C->getOperand(i) != op0) {
10798 op0 = 0;
10799 break;
10800 }
10801 if (op0)
10802 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010803 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010804
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010805 // If extracting a specified index from the vector, see if we can recursively
10806 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010807 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010808 unsigned IndexVal = IdxC->getZExtValue();
10809 unsigned VectorWidth =
10810 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10811
10812 // If this is extracting an invalid index, turn this into undef, to avoid
10813 // crashing the code below.
10814 if (IndexVal >= VectorWidth)
10815 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10816
Chris Lattner867b99f2006-10-05 06:55:50 +000010817 // This instruction only demands the single element from the input vector.
10818 // If the input vector has a single use, simplify it based on this use
10819 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010820 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010821 uint64_t UndefElts;
10822 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010823 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010824 UndefElts)) {
10825 EI.setOperand(0, V);
10826 return &EI;
10827 }
10828 }
10829
Reid Spencerb83eb642006-10-20 07:07:24 +000010830 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010831 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010832
10833 // If the this extractelement is directly using a bitcast from a vector of
10834 // the same number of elements, see if we can find the source element from
10835 // it. In this case, we will end up needing to bitcast the scalars.
10836 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10837 if (const VectorType *VT =
10838 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10839 if (VT->getNumElements() == VectorWidth)
10840 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10841 return new BitCastInst(Elt, EI.getType());
10842 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010843 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010844
Chris Lattner73fa49d2006-05-25 22:53:38 +000010845 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010846 if (I->hasOneUse()) {
10847 // Push extractelement into predecessor operation if legal and
10848 // profitable to do so
10849 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010850 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10851 if (CheapToScalarize(BO, isConstantElt)) {
10852 ExtractElementInst *newEI0 =
10853 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10854 EI.getName()+".lhs");
10855 ExtractElementInst *newEI1 =
10856 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10857 EI.getName()+".rhs");
10858 InsertNewInstBefore(newEI0, EI);
10859 InsertNewInstBefore(newEI1, EI);
10860 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10861 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010862 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010863 unsigned AS =
10864 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010865 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10866 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010867 GetElementPtrInst *GEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010868 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010869 InsertNewInstBefore(GEP, EI);
10870 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010871 }
10872 }
10873 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10874 // Extracting the inserted element?
10875 if (IE->getOperand(2) == EI.getOperand(1))
10876 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10877 // If the inserted and extracted elements are constants, they must not
10878 // be the same value, extract from the pre-inserted value instead.
10879 if (isa<Constant>(IE->getOperand(2)) &&
10880 isa<Constant>(EI.getOperand(1))) {
10881 AddUsesToWorkList(EI);
10882 EI.setOperand(0, IE->getOperand(0));
10883 return &EI;
10884 }
10885 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10886 // If this is extracting an element from a shufflevector, figure out where
10887 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010888 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10889 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010890 Value *Src;
10891 if (SrcIdx < SVI->getType()->getNumElements())
10892 Src = SVI->getOperand(0);
10893 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10894 SrcIdx -= SVI->getType()->getNumElements();
10895 Src = SVI->getOperand(1);
10896 } else {
10897 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010898 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010899 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010900 }
10901 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010902 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010903 return 0;
10904}
10905
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010906/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10907/// elements from either LHS or RHS, return the shuffle mask and true.
10908/// Otherwise, return false.
10909static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10910 std::vector<Constant*> &Mask) {
10911 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10912 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010913 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010914
10915 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010916 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010917 return true;
10918 } else if (V == LHS) {
10919 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010920 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010921 return true;
10922 } else if (V == RHS) {
10923 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010924 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010925 return true;
10926 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10927 // If this is an insert of an extract from some other vector, include it.
10928 Value *VecOp = IEI->getOperand(0);
10929 Value *ScalarOp = IEI->getOperand(1);
10930 Value *IdxOp = IEI->getOperand(2);
10931
Chris Lattnerd929f062006-04-27 21:14:21 +000010932 if (!isa<ConstantInt>(IdxOp))
10933 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010934 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010935
10936 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10937 // Okay, we can handle this if the vector we are insertinting into is
10938 // transitively ok.
10939 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10940 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010941 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010942 return true;
10943 }
10944 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10945 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010946 EI->getOperand(0)->getType() == V->getType()) {
10947 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010948 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010949
10950 // This must be extracting from either LHS or RHS.
10951 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10952 // Okay, we can handle this if the vector we are insertinting into is
10953 // transitively ok.
10954 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10955 // If so, update the mask to reflect the inserted value.
10956 if (EI->getOperand(0) == LHS) {
10957 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010958 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010959 } else {
10960 assert(EI->getOperand(0) == RHS);
10961 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010962 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010963
10964 }
10965 return true;
10966 }
10967 }
10968 }
10969 }
10970 }
10971 // TODO: Handle shufflevector here!
10972
10973 return false;
10974}
10975
10976/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10977/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10978/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010979static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010980 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010981 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010982 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010983 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010984 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010985
10986 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010987 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010988 return V;
10989 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010990 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010991 return V;
10992 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10993 // If this is an insert of an extract from some other vector, include it.
10994 Value *VecOp = IEI->getOperand(0);
10995 Value *ScalarOp = IEI->getOperand(1);
10996 Value *IdxOp = IEI->getOperand(2);
10997
10998 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10999 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11000 EI->getOperand(0)->getType() == V->getType()) {
11001 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011002 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11003 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011004
11005 // Either the extracted from or inserted into vector must be RHSVec,
11006 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011007 if (EI->getOperand(0) == RHS || RHS == 0) {
11008 RHS = EI->getOperand(0);
11009 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011010 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011011 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011012 return V;
11013 }
11014
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011015 if (VecOp == RHS) {
11016 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011017 // Everything but the extracted element is replaced with the RHS.
11018 for (unsigned i = 0; i != NumElts; ++i) {
11019 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011020 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011021 }
11022 return V;
11023 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011024
11025 // If this insertelement is a chain that comes from exactly these two
11026 // vectors, return the vector and the effective shuffle.
11027 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11028 return EI->getOperand(0);
11029
Chris Lattnerefb47352006-04-15 01:39:45 +000011030 }
11031 }
11032 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011033 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011034
11035 // Otherwise, can't do anything fancy. Return an identity vector.
11036 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011037 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011038 return V;
11039}
11040
11041Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11042 Value *VecOp = IE.getOperand(0);
11043 Value *ScalarOp = IE.getOperand(1);
11044 Value *IdxOp = IE.getOperand(2);
11045
Chris Lattner599ded12007-04-09 01:11:16 +000011046 // Inserting an undef or into an undefined place, remove this.
11047 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11048 ReplaceInstUsesWith(IE, VecOp);
11049
Chris Lattnerefb47352006-04-15 01:39:45 +000011050 // If the inserted element was extracted from some other vector, and if the
11051 // indexes are constant, try to turn this into a shufflevector operation.
11052 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11053 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11054 EI->getOperand(0)->getType() == IE.getType()) {
11055 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011056 unsigned ExtractedIdx =
11057 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011058 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011059
11060 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11061 return ReplaceInstUsesWith(IE, VecOp);
11062
11063 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11064 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11065
11066 // If we are extracting a value from a vector, then inserting it right
11067 // back into the same place, just use the input vector.
11068 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11069 return ReplaceInstUsesWith(IE, VecOp);
11070
11071 // We could theoretically do this for ANY input. However, doing so could
11072 // turn chains of insertelement instructions into a chain of shufflevector
11073 // instructions, and right now we do not merge shufflevectors. As such,
11074 // only do this in a situation where it is clear that there is benefit.
11075 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11076 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11077 // the values of VecOp, except then one read from EIOp0.
11078 // Build a new shuffle mask.
11079 std::vector<Constant*> Mask;
11080 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011081 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011082 else {
11083 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011084 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011085 NumVectorElts));
11086 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011087 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011088 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011089 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011090 }
11091
11092 // If this insertelement isn't used by some other insertelement, turn it
11093 // (and any insertelements it points to), into one big shuffle.
11094 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11095 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011096 Value *RHS = 0;
11097 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11098 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11099 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011100 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011101 }
11102 }
11103 }
11104
11105 return 0;
11106}
11107
11108
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011109Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11110 Value *LHS = SVI.getOperand(0);
11111 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011112 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011113
11114 bool MadeChange = false;
11115
Chris Lattner867b99f2006-10-05 06:55:50 +000011116 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011117 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011118 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11119
Chris Lattnere4929dd2007-01-05 07:36:08 +000011120 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011121 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011122 if (isa<UndefValue>(SVI.getOperand(1))) {
11123 // Scan to see if there are any references to the RHS. If so, replace them
11124 // with undef element refs and set MadeChange to true.
11125 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11126 if (Mask[i] >= e && Mask[i] != 2*e) {
11127 Mask[i] = 2*e;
11128 MadeChange = true;
11129 }
11130 }
11131
11132 if (MadeChange) {
11133 // Remap any references to RHS to use LHS.
11134 std::vector<Constant*> Elts;
11135 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11136 if (Mask[i] == 2*e)
11137 Elts.push_back(UndefValue::get(Type::Int32Ty));
11138 else
11139 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11140 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011141 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011142 }
11143 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011144
Chris Lattner863bcff2006-05-25 23:48:38 +000011145 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11146 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11147 if (LHS == RHS || isa<UndefValue>(LHS)) {
11148 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011149 // shuffle(undef,undef,mask) -> undef.
11150 return ReplaceInstUsesWith(SVI, LHS);
11151 }
11152
Chris Lattner863bcff2006-05-25 23:48:38 +000011153 // Remap any references to RHS to use LHS.
11154 std::vector<Constant*> Elts;
11155 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011156 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011157 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011158 else {
11159 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11160 (Mask[i] < e && isa<UndefValue>(LHS)))
11161 Mask[i] = 2*e; // Turn into undef.
11162 else
11163 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011164 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011165 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011166 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011167 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011168 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011169 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011170 LHS = SVI.getOperand(0);
11171 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011172 MadeChange = true;
11173 }
11174
Chris Lattner7b2e27922006-05-26 00:29:06 +000011175 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011176 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011177
Chris Lattner863bcff2006-05-25 23:48:38 +000011178 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11179 if (Mask[i] >= e*2) continue; // Ignore undef values.
11180 // Is this an identity shuffle of the LHS value?
11181 isLHSID &= (Mask[i] == i);
11182
11183 // Is this an identity shuffle of the RHS value?
11184 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011185 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011186
Chris Lattner863bcff2006-05-25 23:48:38 +000011187 // Eliminate identity shuffles.
11188 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11189 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011190
Chris Lattner7b2e27922006-05-26 00:29:06 +000011191 // If the LHS is a shufflevector itself, see if we can combine it with this
11192 // one without producing an unusual shuffle. Here we are really conservative:
11193 // we are absolutely afraid of producing a shuffle mask not in the input
11194 // program, because the code gen may not be smart enough to turn a merged
11195 // shuffle into two specific shuffles: it may produce worse code. As such,
11196 // we only merge two shuffles if the result is one of the two input shuffle
11197 // masks. In this case, merging the shuffles just removes one instruction,
11198 // which we know is safe. This is good for things like turning:
11199 // (splat(splat)) -> splat.
11200 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11201 if (isa<UndefValue>(RHS)) {
11202 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11203
11204 std::vector<unsigned> NewMask;
11205 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11206 if (Mask[i] >= 2*e)
11207 NewMask.push_back(2*e);
11208 else
11209 NewMask.push_back(LHSMask[Mask[i]]);
11210
11211 // If the result mask is equal to the src shuffle or this shuffle mask, do
11212 // the replacement.
11213 if (NewMask == LHSMask || NewMask == Mask) {
11214 std::vector<Constant*> Elts;
11215 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11216 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011217 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011218 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011219 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011220 }
11221 }
11222 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11223 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011224 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011225 }
11226 }
11227 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011228
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011229 return MadeChange ? &SVI : 0;
11230}
11231
11232
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011233
Chris Lattnerea1c4542004-12-08 23:43:58 +000011234
11235/// TryToSinkInstruction - Try to move the specified instruction from its
11236/// current block into the beginning of DestBlock, which can only happen if it's
11237/// safe to move the instruction past all of the instructions between it and the
11238/// end of its block.
11239static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11240 assert(I->hasOneUse() && "Invariants didn't hold!");
11241
Chris Lattner108e9022005-10-27 17:13:11 +000011242 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011243 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11244 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011245
Chris Lattnerea1c4542004-12-08 23:43:58 +000011246 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011247 if (isa<AllocaInst>(I) && I->getParent() ==
11248 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011249 return false;
11250
Chris Lattner96a52a62004-12-09 07:14:34 +000011251 // We can only sink load instructions if there is nothing between the load and
11252 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011253 if (I->mayReadFromMemory()) {
11254 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011255 Scan != E; ++Scan)
11256 if (Scan->mayWriteToMemory())
11257 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011258 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011259
11260 BasicBlock::iterator InsertPos = DestBlock->begin();
11261 while (isa<PHINode>(InsertPos)) ++InsertPos;
11262
Chris Lattner4bc5f802005-08-08 19:11:57 +000011263 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011264 ++NumSunkInst;
11265 return true;
11266}
11267
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011268
11269/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11270/// all reachable code to the worklist.
11271///
11272/// This has a couple of tricks to make the code faster and more powerful. In
11273/// particular, we constant fold and DCE instructions as we go, to avoid adding
11274/// them to the worklist (this significantly speeds up instcombine on code where
11275/// many instructions are dead or constant). Additionally, if we find a branch
11276/// whose condition is a known constant, we only visit the reachable successors.
11277///
11278static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011279 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011280 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011281 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011282 std::vector<BasicBlock*> Worklist;
11283 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011284
Chris Lattner2c7718a2007-03-23 19:17:18 +000011285 while (!Worklist.empty()) {
11286 BB = Worklist.back();
11287 Worklist.pop_back();
11288
11289 // We have now visited this block! If we've already been here, ignore it.
11290 if (!Visited.insert(BB)) continue;
11291
11292 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11293 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011294
Chris Lattner2c7718a2007-03-23 19:17:18 +000011295 // DCE instruction if trivially dead.
11296 if (isInstructionTriviallyDead(Inst)) {
11297 ++NumDeadInst;
11298 DOUT << "IC: DCE: " << *Inst;
11299 Inst->eraseFromParent();
11300 continue;
11301 }
11302
11303 // ConstantProp instruction if trivially constant.
11304 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11305 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11306 Inst->replaceAllUsesWith(C);
11307 ++NumConstProp;
11308 Inst->eraseFromParent();
11309 continue;
11310 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011311
Chris Lattner2c7718a2007-03-23 19:17:18 +000011312 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011313 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011314
11315 // Recursively visit successors. If this is a branch or switch on a
11316 // constant, only visit the reachable successor.
11317 TerminatorInst *TI = BB->getTerminator();
11318 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11319 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11320 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011321 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011322 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011323 continue;
11324 }
11325 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11326 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11327 // See if this is an explicit destination.
11328 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11329 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011330 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011331 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011332 continue;
11333 }
11334
11335 // Otherwise it is the default destination.
11336 Worklist.push_back(SI->getSuccessor(0));
11337 continue;
11338 }
11339 }
11340
11341 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11342 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011343 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011344}
11345
Chris Lattnerec9c3582007-03-03 02:04:50 +000011346bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011347 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011348 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011349
11350 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11351 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011352
Chris Lattnerb3d59702005-07-07 20:40:38 +000011353 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011354 // Do a depth-first traversal of the function, populate the worklist with
11355 // the reachable instructions. Ignore blocks that are not reachable. Keep
11356 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011357 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011358 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011359
Chris Lattnerb3d59702005-07-07 20:40:38 +000011360 // Do a quick scan over the function. If we find any blocks that are
11361 // unreachable, remove any instructions inside of them. This prevents
11362 // the instcombine code from having to deal with some bad special cases.
11363 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11364 if (!Visited.count(BB)) {
11365 Instruction *Term = BB->getTerminator();
11366 while (Term != BB->begin()) { // Remove instrs bottom-up
11367 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011368
Bill Wendlingb7427032006-11-26 09:46:52 +000011369 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011370 ++NumDeadInst;
11371
11372 if (!I->use_empty())
11373 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11374 I->eraseFromParent();
11375 }
11376 }
11377 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011378
Chris Lattnerdbab3862007-03-02 21:28:56 +000011379 while (!Worklist.empty()) {
11380 Instruction *I = RemoveOneFromWorkList();
11381 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011382
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011383 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011384 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011385 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011386 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011387 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011388 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011389
Bill Wendlingb7427032006-11-26 09:46:52 +000011390 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011391
11392 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011393 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011394 continue;
11395 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011396
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011397 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011398 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011399 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011400
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011401 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011402 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011403 ReplaceInstUsesWith(*I, C);
11404
Chris Lattner62b14df2002-09-02 04:59:56 +000011405 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011406 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011407 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011408 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011409 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011410
Chris Lattnerea1c4542004-12-08 23:43:58 +000011411 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011412 // FIXME: Remove GetResultInst test when first class support for aggregates
11413 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011414 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011415 BasicBlock *BB = I->getParent();
11416 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11417 if (UserParent != BB) {
11418 bool UserIsSuccessor = false;
11419 // See if the user is one of our successors.
11420 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11421 if (*SI == UserParent) {
11422 UserIsSuccessor = true;
11423 break;
11424 }
11425
11426 // If the user is one of our immediate successors, and if that successor
11427 // only has us as a predecessors (we'd have to split the critical edge
11428 // otherwise), we can keep going.
11429 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11430 next(pred_begin(UserParent)) == pred_end(UserParent))
11431 // Okay, the CFG is simple enough, try to sink this instruction.
11432 Changed |= TryToSinkInstruction(I, UserParent);
11433 }
11434 }
11435
Chris Lattner8a2a3112001-12-14 16:52:21 +000011436 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011437#ifndef NDEBUG
11438 std::string OrigI;
11439#endif
11440 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011441 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011442 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011443 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011444 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011445 DOUT << "IC: Old = " << *I
11446 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011447
Chris Lattnerf523d062004-06-09 05:08:07 +000011448 // Everything uses the new instruction now.
11449 I->replaceAllUsesWith(Result);
11450
11451 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011452 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011453 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011454
Chris Lattner6934a042007-02-11 01:23:03 +000011455 // Move the name to the new instruction first.
11456 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011457
11458 // Insert the new instruction into the basic block...
11459 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011460 BasicBlock::iterator InsertPos = I;
11461
11462 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11463 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11464 ++InsertPos;
11465
11466 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011467
Chris Lattner00d51312004-05-01 23:27:23 +000011468 // Make sure that we reprocess all operands now that we reduced their
11469 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011470 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011471
Chris Lattnerf523d062004-06-09 05:08:07 +000011472 // Instructions can end up on the worklist more than once. Make sure
11473 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011474 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011475
11476 // Erase the old instruction.
11477 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011478 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011479#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011480 DOUT << "IC: Mod = " << OrigI
11481 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011482#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011483
Chris Lattner90ac28c2002-08-02 19:29:35 +000011484 // If the instruction was modified, it's possible that it is now dead.
11485 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011486 if (isInstructionTriviallyDead(I)) {
11487 // Make sure we process all operands now that we are reducing their
11488 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011489 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011490
Chris Lattner00d51312004-05-01 23:27:23 +000011491 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011492 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011493 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011494 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011495 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011496 AddToWorkList(I);
11497 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011498 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011499 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011500 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011501 }
11502 }
11503
Chris Lattnerec9c3582007-03-03 02:04:50 +000011504 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011505
11506 // Do an explicit clear, this shrinks the map if needed.
11507 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011508 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011509}
11510
Chris Lattnerec9c3582007-03-03 02:04:50 +000011511
11512bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011513 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11514
Chris Lattnerec9c3582007-03-03 02:04:50 +000011515 bool EverMadeChange = false;
11516
11517 // Iterate while there is work to do.
11518 unsigned Iteration = 0;
11519 while (DoOneIteration(F, Iteration++))
11520 EverMadeChange = true;
11521 return EverMadeChange;
11522}
11523
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011524FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011525 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011526}
Brian Gaeked0fde302003-11-11 22:41:34 +000011527