blob: b8270a0bcd37ad62ad080c6c7e0e103f9b6e2b6c [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 Lattner173234a2008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000049#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000051#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000052#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000053#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000055#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000056#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000060#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000061#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000062#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000063using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000064using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000073 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000077 std::vector<Instruction*> Worklist;
78 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000079 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000080 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000082 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000083 InstCombiner() : FunctionPass((intptr_t)&ID) {}
84
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
88 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
89 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000109
Chris Lattnerdbab3862007-03-02 21:28:56 +0000110
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000115 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000118 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000119 }
120
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
125 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000127 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
139 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000141 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000142 // Set the operand to undef to drop the use.
143 I.setOperand(i, UndefValue::get(Op->getType()));
144 }
145
146 return R;
147 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000148
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000149 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000150 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000151
152 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153
Chris Lattner97e52e42002-04-28 21:27:06 +0000154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000155 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000156 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000157 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000158 }
159
Chris Lattner28977af2004-04-05 01:30:19 +0000160 TargetData &getTargetData() const { return *TD; }
161
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000166 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000168 //
Chris Lattner7e708292002-06-25 16:13:24 +0000169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
175 Instruction *commonRemTransforms(BinaryOperator &I);
176 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000177 Instruction *commonDivTransforms(BinaryOperator &I);
178 Instruction *commonIDivTransforms(BinaryOperator &I);
179 Instruction *visitUDiv(BinaryOperator &I);
180 Instruction *visitSDiv(BinaryOperator &I);
181 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000182 Instruction *visitAnd(BinaryOperator &I);
183 Instruction *visitOr (BinaryOperator &I);
184 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000185 Instruction *visitShl(BinaryOperator &I);
186 Instruction *visitAShr(BinaryOperator &I);
187 Instruction *visitLShr(BinaryOperator &I);
188 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000189 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
190 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000191 Instruction *visitFCmpInst(FCmpInst &I);
192 Instruction *visitICmpInst(ICmpInst &I);
193 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000194 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
195 Instruction *LHS,
196 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000197 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000199
Reid Spencere4d87aa2006-12-23 06:05:41 +0000200 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
201 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000202 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000203 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000204 Instruction *commonCastTransforms(CastInst &CI);
205 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000206 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000207 Instruction *visitTrunc(TruncInst &CI);
208 Instruction *visitZExt(ZExtInst &CI);
209 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000210 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000211 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000212 Instruction *visitFPToUI(FPToUIInst &FI);
213 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000214 Instruction *visitUIToFP(CastInst &CI);
215 Instruction *visitSIToFP(CastInst &CI);
216 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000217 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000218 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000219 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
220 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000221 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000222 Instruction *visitCallInst(CallInst &CI);
223 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000224 Instruction *visitPHINode(PHINode &PN);
225 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000226 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000227 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000228 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000229 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000230 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000231 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000232 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000233 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000234 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000235 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000236
237 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000238 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000239
Chris Lattner9fe38862003-06-19 17:00:31 +0000240 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000241 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000242 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000243 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000244 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
245 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000246 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000247
Chris Lattner28977af2004-04-05 01:30:19 +0000248 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000249 // InsertNewInstBefore - insert an instruction New before instruction Old
250 // in the program. Add the new instruction to the worklist.
251 //
Chris Lattner955f3312004-09-28 21:48:02 +0000252 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000253 assert(New && New->getParent() == 0 &&
254 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000255 BasicBlock *BB = Old.getParent();
256 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000257 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000258 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000259 }
260
Chris Lattner0c967662004-09-24 15:21:34 +0000261 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
262 /// This also adds the cast to the worklist. Finally, this returns the
263 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000264 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
265 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000266 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000267
Chris Lattnere2ed0572006-04-06 19:19:17 +0000268 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000269 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000270
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000271 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000272 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000273 return C;
274 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000275
276 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
277 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
278 }
279
Chris Lattner0c967662004-09-24 15:21:34 +0000280
Chris Lattner8b170942002-08-09 23:47:40 +0000281 // ReplaceInstUsesWith - This method is to be used when an instruction is
282 // found to be dead, replacable with another preexisting expression. Here
283 // we add all uses of I to the worklist, replace all uses of I with the new
284 // value, then return I, so that the inst combiner will know that I was
285 // modified.
286 //
287 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000288 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000289 if (&I != V) {
290 I.replaceAllUsesWith(V);
291 return &I;
292 } else {
293 // If we are replacing the instruction with itself, this must be in a
294 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000295 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000296 return &I;
297 }
Chris Lattner8b170942002-08-09 23:47:40 +0000298 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000299
Chris Lattner6dce1a72006-02-07 06:56:34 +0000300 // UpdateValueUsesWith - This method is to be used when an value is
301 // found to be replacable with another preexisting expression or was
302 // updated. Here we add all uses of I to the worklist, replace all uses of
303 // I with the new value (unless the instruction was just updated), then
304 // return true, so that the inst combiner will know that I was modified.
305 //
306 bool UpdateValueUsesWith(Value *Old, Value *New) {
307 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
308 if (Old != New)
309 Old->replaceAllUsesWith(New);
310 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000311 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000312 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000313 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000314 return true;
315 }
316
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000317 // EraseInstFromFunction - When dealing with an instruction that has side
318 // effects or produces a void value, we can't rely on DCE to delete the
319 // instruction. Instead, visit methods should return the value returned by
320 // this function.
321 Instruction *EraseInstFromFunction(Instruction &I) {
322 assert(I.use_empty() && "Cannot erase instruction that is used!");
323 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000324 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000325 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000326 return 0; // Don't do anything with FI
327 }
Chris Lattner173234a2008-06-02 01:18:21 +0000328
329 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330 APInt &KnownOne, unsigned Depth = 0) const {
331 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332 }
333
334 bool MaskedValueIsZero(Value *V, const APInt &Mask,
335 unsigned Depth = 0) const {
336 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337 }
338 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339 return llvm::ComputeNumSignBits(Op, TD, Depth);
340 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000341
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000342 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000343 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
344 /// InsertBefore instruction. This is specialized a bit to avoid inserting
345 /// casts that are known to not do anything...
346 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000347 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
348 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000349 Instruction *InsertBefore);
350
Reid Spencere4d87aa2006-12-23 06:05:41 +0000351 /// SimplifyCommutative - This performs a few simplifications for
352 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000353 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000354
Reid Spencere4d87aa2006-12-23 06:05:41 +0000355 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
356 /// most-complex to least-complex order.
357 bool SimplifyCompare(CmpInst &I);
358
Reid Spencer2ec619a2007-03-23 21:24:59 +0000359 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
360 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000361 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
362 APInt& KnownZero, APInt& KnownOne,
363 unsigned Depth = 0);
364
Chris Lattner867b99f2006-10-05 06:55:50 +0000365 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
366 uint64_t &UndefElts, unsigned Depth = 0);
367
Chris Lattner4e998b22004-09-29 05:07:12 +0000368 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369 // PHI node as operand #0, see if we can fold the instruction into the PHI
370 // (which is only possible if all operands to the PHI are constants).
371 Instruction *FoldOpIntoPhi(Instruction &I);
372
Chris Lattnerbac32862004-11-14 19:13:23 +0000373 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374 // operator and they all are only used by the PHI, PHI together their
375 // inputs, and do the operation once, to the result of the PHI.
376 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000377 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378
379
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000380 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000382
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000383 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000384 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000385 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000386 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000387 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000388 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000389 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000390 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000391 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000392
Chris Lattnerafe91a52006-06-15 19:07:26 +0000393
Reid Spencerc55b2432006-12-13 18:21:21 +0000394 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000395
Dan Gohmaneee962e2008-04-10 18:43:06 +0000396 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
397 unsigned CastOpc,
398 int &NumCastsRemoved);
399 unsigned GetOrEnforceKnownAlignment(Value *V,
400 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000401
402 // visitExtractValue helpers
403 Value *FindScalarValue(Value *V,
404 const unsigned *idx_begin,
405 const unsigned *idx_end,
406 Instruction &InsertBefore);
407 Value *BuildSubAggregate(Value *From,
408 const unsigned *idx_begin,
409 const unsigned *idx_end,
410 Instruction &InsertBefore);
411 Value *BuildSubAggregate(Value *From,
412 Value* To,
413 const Type *IndexedType,
414 SmallVector<unsigned, 10> &Idxs,
415 unsigned IdxSkip,
416 Instruction &InsertBefore);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000417 };
418}
419
Dan Gohman844731a2008-05-13 00:00:25 +0000420char InstCombiner::ID = 0;
421static RegisterPass<InstCombiner>
422X("instcombine", "Combine redundant instructions");
423
Chris Lattner4f98c562003-03-10 21:43:22 +0000424// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000425// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000426static unsigned getComplexity(Value *V) {
427 if (isa<Instruction>(V)) {
428 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000429 return 3;
430 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000431 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000432 if (isa<Argument>(V)) return 3;
433 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000434}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000435
Chris Lattnerc8802d22003-03-11 00:12:48 +0000436// isOnlyUse - Return true if this instruction will be deleted if we stop using
437// it.
438static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000439 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000440}
441
Chris Lattner4cb170c2004-02-23 06:38:22 +0000442// getPromotedType - Return the specified type promoted as it would be to pass
443// though a va_arg area...
444static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000445 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
446 if (ITy->getBitWidth() < 32)
447 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000448 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000449 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000450}
451
Reid Spencer3da59db2006-11-27 01:05:10 +0000452/// getBitCastOperand - If the specified operand is a CastInst or a constant
453/// expression bitcast, return the operand value, otherwise return null.
454static Value *getBitCastOperand(Value *V) {
455 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000456 return I->getOperand(0);
457 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000458 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000459 return CE->getOperand(0);
460 return 0;
461}
462
Reid Spencer3da59db2006-11-27 01:05:10 +0000463/// This function is a wrapper around CastInst::isEliminableCastPair. It
464/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000465static Instruction::CastOps
466isEliminableCastPair(
467 const CastInst *CI, ///< The first cast instruction
468 unsigned opcode, ///< The opcode of the second cast instruction
469 const Type *DstTy, ///< The target type for the second cast instruction
470 TargetData *TD ///< The target data for pointer size
471) {
472
473 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
474 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000475
Reid Spencer3da59db2006-11-27 01:05:10 +0000476 // Get the opcodes of the two Cast instructions
477 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
478 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000479
Reid Spencer3da59db2006-11-27 01:05:10 +0000480 return Instruction::CastOps(
481 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
482 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000483}
484
485/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
486/// in any code being generated. It does not require codegen if V is simple
487/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000488static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
489 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000490 if (V->getType() == Ty || isa<Constant>(V)) return false;
491
Chris Lattner01575b72006-05-25 23:24:33 +0000492 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000493 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000494 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000495 return false;
496 return true;
497}
498
499/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
500/// InsertBefore instruction. This is specialized a bit to avoid inserting
501/// casts that are known to not do anything...
502///
Reid Spencer17212df2006-12-12 09:18:51 +0000503Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
504 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000505 Instruction *InsertBefore) {
506 if (V->getType() == DestTy) return V;
507 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000508 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000509
Reid Spencer17212df2006-12-12 09:18:51 +0000510 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000511}
512
Chris Lattner4f98c562003-03-10 21:43:22 +0000513// SimplifyCommutative - This performs a few simplifications for commutative
514// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000515//
Chris Lattner4f98c562003-03-10 21:43:22 +0000516// 1. Order operands such that they are listed from right (least complex) to
517// left (most complex). This puts constants before unary operators before
518// binary operators.
519//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000520// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
521// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000522//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000523bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000524 bool Changed = false;
525 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
526 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000527
Chris Lattner4f98c562003-03-10 21:43:22 +0000528 if (!I.isAssociative()) return Changed;
529 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000530 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
531 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
532 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000533 Constant *Folded = ConstantExpr::get(I.getOpcode(),
534 cast<Constant>(I.getOperand(1)),
535 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000536 I.setOperand(0, Op->getOperand(0));
537 I.setOperand(1, Folded);
538 return true;
539 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
540 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
541 isOnlyUse(Op) && isOnlyUse(Op1)) {
542 Constant *C1 = cast<Constant>(Op->getOperand(1));
543 Constant *C2 = cast<Constant>(Op1->getOperand(1));
544
545 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000546 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000547 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000548 Op1->getOperand(0),
549 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000550 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000551 I.setOperand(0, New);
552 I.setOperand(1, Folded);
553 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000554 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000555 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000556 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000557}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000558
Reid Spencere4d87aa2006-12-23 06:05:41 +0000559/// SimplifyCompare - For a CmpInst this function just orders the operands
560/// so that theyare listed from right (least complex) to left (most complex).
561/// This puts constants before unary operators before binary operators.
562bool InstCombiner::SimplifyCompare(CmpInst &I) {
563 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
564 return false;
565 I.swapOperands();
566 // Compare instructions are not associative so there's nothing else we can do.
567 return true;
568}
569
Chris Lattner8d969642003-03-10 23:06:50 +0000570// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
571// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000572//
Chris Lattner8d969642003-03-10 23:06:50 +0000573static inline Value *dyn_castNegVal(Value *V) {
574 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000575 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000576
Chris Lattner0ce85802004-12-14 20:08:06 +0000577 // Constants can be considered to be negated values if they can be folded.
578 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
579 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000580
581 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
582 if (C->getType()->getElementType()->isInteger())
583 return ConstantExpr::getNeg(C);
584
Chris Lattner8d969642003-03-10 23:06:50 +0000585 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000586}
587
Chris Lattner8d969642003-03-10 23:06:50 +0000588static inline Value *dyn_castNotVal(Value *V) {
589 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000590 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000591
592 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000593 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000594 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000595 return 0;
596}
597
Chris Lattnerc8802d22003-03-11 00:12:48 +0000598// dyn_castFoldableMul - If this value is a multiply that can be folded into
599// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000600// non-constant operand of the multiply, and set CST to point to the multiplier.
601// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000602//
Chris Lattner50af16a2004-11-13 19:50:12 +0000603static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000604 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000605 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000606 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000607 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000608 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000609 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000610 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000611 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000612 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000613 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000614 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000615 return I->getOperand(0);
616 }
617 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000618 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000619}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000620
Chris Lattner574da9b2005-01-13 20:14:25 +0000621/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
622/// expression, return it.
623static User *dyn_castGetElementPtr(Value *V) {
624 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
625 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
626 if (CE->getOpcode() == Instruction::GetElementPtr)
627 return cast<User>(V);
628 return false;
629}
630
Dan Gohmaneee962e2008-04-10 18:43:06 +0000631/// getOpcode - If this is an Instruction or a ConstantExpr, return the
632/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000633static unsigned getOpcode(const Value *V) {
634 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000635 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000636 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000637 return CE->getOpcode();
638 // Use UserOp1 to mean there's no opcode.
639 return Instruction::UserOp1;
640}
641
Reid Spencer7177c3a2007-03-25 05:33:51 +0000642/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000643static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000644 APInt Val(C->getValue());
645 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000646}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000647/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000648static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000649 APInt Val(C->getValue());
650 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000651}
652/// Add - Add two ConstantInts together
653static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
654 return ConstantInt::get(C1->getValue() + C2->getValue());
655}
656/// And - Bitwise AND two ConstantInts together
657static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
658 return ConstantInt::get(C1->getValue() & C2->getValue());
659}
660/// Subtract - Subtract one ConstantInt from another
661static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
662 return ConstantInt::get(C1->getValue() - C2->getValue());
663}
664/// Multiply - Multiply two ConstantInts together
665static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
666 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000667}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000668/// MultiplyOverflows - True if the multiply can not be expressed in an int
669/// this size.
670static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
671 uint32_t W = C1->getBitWidth();
672 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
673 if (sign) {
674 LHSExt.sext(W * 2);
675 RHSExt.sext(W * 2);
676 } else {
677 LHSExt.zext(W * 2);
678 RHSExt.zext(W * 2);
679 }
680
681 APInt MulExt = LHSExt * RHSExt;
682
683 if (sign) {
684 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
685 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
686 return MulExt.slt(Min) || MulExt.sgt(Max);
687 } else
688 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
689}
Chris Lattner955f3312004-09-28 21:48:02 +0000690
Reid Spencere7816b52007-03-08 01:52:58 +0000691
Chris Lattner255d8912006-02-11 09:31:47 +0000692/// ShrinkDemandedConstant - Check to see if the specified operand of the
693/// specified instruction is a constant integer. If so, check to see if there
694/// are any bits set in the constant that are not demanded. If so, shrink the
695/// constant and return true.
696static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000697 APInt Demanded) {
698 assert(I && "No instruction?");
699 assert(OpNo < I->getNumOperands() && "Operand index too large");
700
701 // If the operand is not a constant integer, nothing to do.
702 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
703 if (!OpC) return false;
704
705 // If there are no bits set that aren't demanded, nothing to do.
706 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
707 if ((~Demanded & OpC->getValue()) == 0)
708 return false;
709
710 // This instruction is producing bits that are not demanded. Shrink the RHS.
711 Demanded &= OpC->getValue();
712 I->setOperand(OpNo, ConstantInt::get(Demanded));
713 return true;
714}
715
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000716// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
717// set of known zero and one bits, compute the maximum and minimum values that
718// could have the specified known zero and known one bits, returning them in
719// min/max.
720static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000721 const APInt& KnownZero,
722 const APInt& KnownOne,
723 APInt& Min, APInt& Max) {
724 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
725 assert(KnownZero.getBitWidth() == BitWidth &&
726 KnownOne.getBitWidth() == BitWidth &&
727 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
728 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000729 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000730
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000731 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
732 // bit if it is unknown.
733 Min = KnownOne;
734 Max = KnownOne|UnknownBits;
735
Zhou Sheng4acf1552007-03-28 05:15:57 +0000736 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000737 Min.set(BitWidth-1);
738 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000739 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000740}
741
742// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
743// a set of known zero and one bits, compute the maximum and minimum values that
744// could have the specified known zero and known one bits, returning them in
745// min/max.
746static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000747 const APInt &KnownZero,
748 const APInt &KnownOne,
749 APInt &Min, APInt &Max) {
750 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000751 assert(KnownZero.getBitWidth() == BitWidth &&
752 KnownOne.getBitWidth() == BitWidth &&
753 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
754 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000755 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000756
757 // The minimum value is when the unknown bits are all zeros.
758 Min = KnownOne;
759 // The maximum value is when the unknown bits are all ones.
760 Max = KnownOne|UnknownBits;
761}
Chris Lattner255d8912006-02-11 09:31:47 +0000762
Reid Spencer8cb68342007-03-12 17:25:59 +0000763/// SimplifyDemandedBits - This function attempts to replace V with a simpler
764/// value based on the demanded bits. When this function is called, it is known
765/// that only the bits set in DemandedMask of the result of V are ever used
766/// downstream. Consequently, depending on the mask and V, it may be possible
767/// to replace V with a constant or one of its operands. In such cases, this
768/// function does the replacement and returns true. In all other cases, it
769/// returns false after analyzing the expression and setting KnownOne and known
770/// to be one in the expression. KnownZero contains all the bits that are known
771/// to be zero in the expression. These are provided to potentially allow the
772/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
773/// the expression. KnownOne and KnownZero always follow the invariant that
774/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
775/// the bits in KnownOne and KnownZero may only be accurate for those bits set
776/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
777/// and KnownOne must all be the same.
778bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
779 APInt& KnownZero, APInt& KnownOne,
780 unsigned Depth) {
781 assert(V != 0 && "Null pointer of Value???");
782 assert(Depth <= 6 && "Limit Search Depth");
783 uint32_t BitWidth = DemandedMask.getBitWidth();
784 const IntegerType *VTy = cast<IntegerType>(V->getType());
785 assert(VTy->getBitWidth() == BitWidth &&
786 KnownZero.getBitWidth() == BitWidth &&
787 KnownOne.getBitWidth() == BitWidth &&
788 "Value *V, DemandedMask, KnownZero and KnownOne \
789 must have same BitWidth");
790 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
791 // We know all of the bits for a constant!
792 KnownOne = CI->getValue() & DemandedMask;
793 KnownZero = ~KnownOne & DemandedMask;
794 return false;
795 }
796
Zhou Sheng96704452007-03-14 03:21:24 +0000797 KnownZero.clear();
798 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000799 if (!V->hasOneUse()) { // Other users may use these bits.
800 if (Depth != 0) { // Not at the root.
801 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
802 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
803 return false;
804 }
805 // If this is the root being simplified, allow it to have multiple uses,
806 // just set the DemandedMask to all bits.
807 DemandedMask = APInt::getAllOnesValue(BitWidth);
808 } else if (DemandedMask == 0) { // Not demanding any bits from V.
809 if (V != UndefValue::get(VTy))
810 return UpdateValueUsesWith(V, UndefValue::get(VTy));
811 return false;
812 } else if (Depth == 6) { // Limit search depth.
813 return false;
814 }
815
816 Instruction *I = dyn_cast<Instruction>(V);
817 if (!I) return false; // Only analyze instructions.
818
Reid Spencer8cb68342007-03-12 17:25:59 +0000819 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
820 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
821 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000822 default:
823 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
824 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000825 case Instruction::And:
826 // If either the LHS or the RHS are Zero, the result is zero.
827 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
828 RHSKnownZero, RHSKnownOne, Depth+1))
829 return true;
830 assert((RHSKnownZero & RHSKnownOne) == 0 &&
831 "Bits known to be one AND zero?");
832
833 // If something is known zero on the RHS, the bits aren't demanded on the
834 // LHS.
835 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
836 LHSKnownZero, LHSKnownOne, Depth+1))
837 return true;
838 assert((LHSKnownZero & LHSKnownOne) == 0 &&
839 "Bits known to be one AND zero?");
840
841 // If all of the demanded bits are known 1 on one side, return the other.
842 // These bits cannot contribute to the result of the 'and'.
843 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
844 (DemandedMask & ~LHSKnownZero))
845 return UpdateValueUsesWith(I, I->getOperand(0));
846 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
847 (DemandedMask & ~RHSKnownZero))
848 return UpdateValueUsesWith(I, I->getOperand(1));
849
850 // If all of the demanded bits in the inputs are known zeros, return zero.
851 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
852 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
853
854 // If the RHS is a constant, see if we can simplify it.
855 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
856 return UpdateValueUsesWith(I, I);
857
858 // Output known-1 bits are only known if set in both the LHS & RHS.
859 RHSKnownOne &= LHSKnownOne;
860 // Output known-0 are known to be clear if zero in either the LHS | RHS.
861 RHSKnownZero |= LHSKnownZero;
862 break;
863 case Instruction::Or:
864 // If either the LHS or the RHS are One, the result is One.
865 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
866 RHSKnownZero, RHSKnownOne, Depth+1))
867 return true;
868 assert((RHSKnownZero & RHSKnownOne) == 0 &&
869 "Bits known to be one AND zero?");
870 // If something is known one on the RHS, the bits aren't demanded on the
871 // LHS.
872 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
873 LHSKnownZero, LHSKnownOne, Depth+1))
874 return true;
875 assert((LHSKnownZero & LHSKnownOne) == 0 &&
876 "Bits known to be one AND zero?");
877
878 // If all of the demanded bits are known zero on one side, return the other.
879 // These bits cannot contribute to the result of the 'or'.
880 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
881 (DemandedMask & ~LHSKnownOne))
882 return UpdateValueUsesWith(I, I->getOperand(0));
883 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
884 (DemandedMask & ~RHSKnownOne))
885 return UpdateValueUsesWith(I, I->getOperand(1));
886
887 // If all of the potentially set bits on one side are known to be set on
888 // the other side, just use the 'other' side.
889 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
890 (DemandedMask & (~RHSKnownZero)))
891 return UpdateValueUsesWith(I, I->getOperand(0));
892 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
893 (DemandedMask & (~LHSKnownZero)))
894 return UpdateValueUsesWith(I, I->getOperand(1));
895
896 // If the RHS is a constant, see if we can simplify it.
897 if (ShrinkDemandedConstant(I, 1, DemandedMask))
898 return UpdateValueUsesWith(I, I);
899
900 // Output known-0 bits are only known if clear in both the LHS & RHS.
901 RHSKnownZero &= LHSKnownZero;
902 // Output known-1 are known to be set if set in either the LHS | RHS.
903 RHSKnownOne |= LHSKnownOne;
904 break;
905 case Instruction::Xor: {
906 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
907 RHSKnownZero, RHSKnownOne, Depth+1))
908 return true;
909 assert((RHSKnownZero & RHSKnownOne) == 0 &&
910 "Bits known to be one AND zero?");
911 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
912 LHSKnownZero, LHSKnownOne, Depth+1))
913 return true;
914 assert((LHSKnownZero & LHSKnownOne) == 0 &&
915 "Bits known to be one AND zero?");
916
917 // If all of the demanded bits are known zero on one side, return the other.
918 // These bits cannot contribute to the result of the 'xor'.
919 if ((DemandedMask & RHSKnownZero) == DemandedMask)
920 return UpdateValueUsesWith(I, I->getOperand(0));
921 if ((DemandedMask & LHSKnownZero) == DemandedMask)
922 return UpdateValueUsesWith(I, I->getOperand(1));
923
924 // Output known-0 bits are known if clear or set in both the LHS & RHS.
925 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
926 (RHSKnownOne & LHSKnownOne);
927 // Output known-1 are known to be set if set in only one of the LHS, RHS.
928 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
929 (RHSKnownOne & LHSKnownZero);
930
931 // If all of the demanded bits are known to be zero on one side or the
932 // other, turn this into an *inclusive* or.
933 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
934 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
935 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000936 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +0000937 I->getName());
938 InsertNewInstBefore(Or, *I);
939 return UpdateValueUsesWith(I, Or);
940 }
941
942 // If all of the demanded bits on one side are known, and all of the set
943 // bits on that side are also known to be set on the other side, turn this
944 // into an AND, as we know the bits will be cleared.
945 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
946 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
947 // all known
948 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
949 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
950 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000951 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +0000952 InsertNewInstBefore(And, *I);
953 return UpdateValueUsesWith(I, And);
954 }
955 }
956
957 // If the RHS is a constant, see if we can simplify it.
958 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
959 if (ShrinkDemandedConstant(I, 1, DemandedMask))
960 return UpdateValueUsesWith(I, I);
961
962 RHSKnownZero = KnownZeroOut;
963 RHSKnownOne = KnownOneOut;
964 break;
965 }
966 case Instruction::Select:
967 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
968 RHSKnownZero, RHSKnownOne, Depth+1))
969 return true;
970 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
971 LHSKnownZero, LHSKnownOne, Depth+1))
972 return true;
973 assert((RHSKnownZero & RHSKnownOne) == 0 &&
974 "Bits known to be one AND zero?");
975 assert((LHSKnownZero & LHSKnownOne) == 0 &&
976 "Bits known to be one AND zero?");
977
978 // If the operands are constants, see if we can simplify them.
979 if (ShrinkDemandedConstant(I, 1, DemandedMask))
980 return UpdateValueUsesWith(I, I);
981 if (ShrinkDemandedConstant(I, 2, DemandedMask))
982 return UpdateValueUsesWith(I, I);
983
984 // Only known if known in both the LHS and RHS.
985 RHSKnownOne &= LHSKnownOne;
986 RHSKnownZero &= LHSKnownZero;
987 break;
988 case Instruction::Trunc: {
989 uint32_t truncBf =
990 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +0000991 DemandedMask.zext(truncBf);
992 RHSKnownZero.zext(truncBf);
993 RHSKnownOne.zext(truncBf);
994 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
995 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +0000996 return true;
997 DemandedMask.trunc(BitWidth);
998 RHSKnownZero.trunc(BitWidth);
999 RHSKnownOne.trunc(BitWidth);
1000 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1001 "Bits known to be one AND zero?");
1002 break;
1003 }
1004 case Instruction::BitCast:
1005 if (!I->getOperand(0)->getType()->isInteger())
1006 return false;
1007
1008 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1009 RHSKnownZero, RHSKnownOne, Depth+1))
1010 return true;
1011 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1012 "Bits known to be one AND zero?");
1013 break;
1014 case Instruction::ZExt: {
1015 // Compute the bits in the result that are not present in the input.
1016 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001017 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001018
Zhou Shengd48653a2007-03-29 04:45:55 +00001019 DemandedMask.trunc(SrcBitWidth);
1020 RHSKnownZero.trunc(SrcBitWidth);
1021 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001022 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1023 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001024 return true;
1025 DemandedMask.zext(BitWidth);
1026 RHSKnownZero.zext(BitWidth);
1027 RHSKnownOne.zext(BitWidth);
1028 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1029 "Bits known to be one AND zero?");
1030 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001031 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001032 break;
1033 }
1034 case Instruction::SExt: {
1035 // Compute the bits in the result that are not present in the input.
1036 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001037 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001038
Reid Spencer8cb68342007-03-12 17:25:59 +00001039 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001040 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001041
Zhou Sheng01542f32007-03-29 02:26:30 +00001042 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001043 // If any of the sign extended bits are demanded, we know that the sign
1044 // bit is demanded.
1045 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001046 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001047
Zhou Shengd48653a2007-03-29 04:45:55 +00001048 InputDemandedBits.trunc(SrcBitWidth);
1049 RHSKnownZero.trunc(SrcBitWidth);
1050 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001051 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1052 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001053 return true;
1054 InputDemandedBits.zext(BitWidth);
1055 RHSKnownZero.zext(BitWidth);
1056 RHSKnownOne.zext(BitWidth);
1057 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1058 "Bits known to be one AND zero?");
1059
1060 // If the sign bit of the input is known set or clear, then we know the
1061 // top bits of the result.
1062
1063 // If the input sign bit is known zero, or if the NewBits are not demanded
1064 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001065 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001066 {
1067 // Convert to ZExt cast
1068 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1069 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001070 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001071 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001072 }
1073 break;
1074 }
1075 case Instruction::Add: {
1076 // Figure out what the input bits are. If the top bits of the and result
1077 // are not demanded, then the add doesn't demand them from its input
1078 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001079 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001080
1081 // If there is a constant on the RHS, there are a variety of xformations
1082 // we can do.
1083 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1084 // If null, this should be simplified elsewhere. Some of the xforms here
1085 // won't work if the RHS is zero.
1086 if (RHS->isZero())
1087 break;
1088
1089 // If the top bit of the output is demanded, demand everything from the
1090 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001091 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001092
1093 // Find information about known zero/one bits in the input.
1094 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1095 LHSKnownZero, LHSKnownOne, Depth+1))
1096 return true;
1097
1098 // If the RHS of the add has bits set that can't affect the input, reduce
1099 // the constant.
1100 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1101 return UpdateValueUsesWith(I, I);
1102
1103 // Avoid excess work.
1104 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1105 break;
1106
1107 // Turn it into OR if input bits are zero.
1108 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1109 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001110 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001111 I->getName());
1112 InsertNewInstBefore(Or, *I);
1113 return UpdateValueUsesWith(I, Or);
1114 }
1115
1116 // We can say something about the output known-zero and known-one bits,
1117 // depending on potential carries from the input constant and the
1118 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1119 // bits set and the RHS constant is 0x01001, then we know we have a known
1120 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1121
1122 // To compute this, we first compute the potential carry bits. These are
1123 // the bits which may be modified. I'm not aware of a better way to do
1124 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001125 const APInt& RHSVal = RHS->getValue();
1126 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001127
1128 // Now that we know which bits have carries, compute the known-1/0 sets.
1129
1130 // Bits are known one if they are known zero in one operand and one in the
1131 // other, and there is no input carry.
1132 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1133 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1134
1135 // Bits are known zero if they are known zero in both operands and there
1136 // is no input carry.
1137 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1138 } else {
1139 // If the high-bits of this ADD are not demanded, then it does not demand
1140 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001141 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001142 // Right fill the mask of bits for this ADD to demand the most
1143 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001144 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001145 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1146 LHSKnownZero, LHSKnownOne, Depth+1))
1147 return true;
1148 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1149 LHSKnownZero, LHSKnownOne, Depth+1))
1150 return true;
1151 }
1152 }
1153 break;
1154 }
1155 case Instruction::Sub:
1156 // If the high-bits of this SUB are not demanded, then it does not demand
1157 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001158 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001159 // Right fill the mask of bits for this SUB to demand the most
1160 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001161 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001162 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1164 LHSKnownZero, LHSKnownOne, Depth+1))
1165 return true;
1166 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1167 LHSKnownZero, LHSKnownOne, Depth+1))
1168 return true;
1169 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001170 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1171 // the known zeros and ones.
1172 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001173 break;
1174 case Instruction::Shl:
1175 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001176 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001177 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1178 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001179 RHSKnownZero, RHSKnownOne, Depth+1))
1180 return true;
1181 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1182 "Bits known to be one AND zero?");
1183 RHSKnownZero <<= ShiftAmt;
1184 RHSKnownOne <<= ShiftAmt;
1185 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001186 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001187 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001188 }
1189 break;
1190 case Instruction::LShr:
1191 // For a logical shift right
1192 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001193 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001194
Reid Spencer8cb68342007-03-12 17:25:59 +00001195 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001196 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1197 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001198 RHSKnownZero, RHSKnownOne, Depth+1))
1199 return true;
1200 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1201 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1203 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001204 if (ShiftAmt) {
1205 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001206 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001207 RHSKnownZero |= HighBits; // high bits known zero.
1208 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 }
1210 break;
1211 case Instruction::AShr:
1212 // If this is an arithmetic shift right and only the low-bit is set, we can
1213 // always convert this into a logical shr, even if the shift amount is
1214 // variable. The low bit of the shift cannot be an input sign bit unless
1215 // the shift amount is >= the size of the datatype, which is undefined.
1216 if (DemandedMask == 1) {
1217 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001218 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001219 I->getOperand(0), I->getOperand(1), I->getName());
1220 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1221 return UpdateValueUsesWith(I, NewVal);
1222 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001223
1224 // If the sign bit is the only bit demanded by this ashr, then there is no
1225 // need to do it, the shift doesn't change the high bit.
1226 if (DemandedMask.isSignBit())
1227 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001228
1229 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001230 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001231
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001233 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001234 // If any of the "high bits" are demanded, we should set the sign bit as
1235 // demanded.
1236 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1237 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001238 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001239 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001240 RHSKnownZero, RHSKnownOne, Depth+1))
1241 return true;
1242 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1243 "Bits known to be one AND zero?");
1244 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001245 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1247 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1248
1249 // Handle the sign bits.
1250 APInt SignBit(APInt::getSignBit(BitWidth));
1251 // Adjust to where it is now in the mask.
1252 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1253
1254 // If the input sign bit is known to be zero, or if none of the top bits
1255 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001256 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001257 (HighBits & ~DemandedMask) == HighBits) {
1258 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001259 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001260 I->getOperand(0), SA, I->getName());
1261 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1262 return UpdateValueUsesWith(I, NewVal);
1263 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1264 RHSKnownOne |= HighBits;
1265 }
1266 }
1267 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001268 case Instruction::SRem:
1269 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1270 APInt RA = Rem->getValue();
1271 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001272 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001273 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1274 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1275 LHSKnownZero, LHSKnownOne, Depth+1))
1276 return true;
1277
1278 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1279 LHSKnownZero |= ~LowBits;
1280 else if (LHSKnownOne[BitWidth-1])
1281 LHSKnownOne |= ~LowBits;
1282
1283 KnownZero |= LHSKnownZero & DemandedMask;
1284 KnownOne |= LHSKnownOne & DemandedMask;
1285
1286 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1287 }
1288 }
1289 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001290 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001291 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1292 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001293 if (RA.isPowerOf2()) {
1294 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001295 APInt Mask2 = LowBits & DemandedMask;
1296 KnownZero |= ~LowBits & DemandedMask;
1297 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1298 KnownZero, KnownOne, Depth+1))
1299 return true;
1300
1301 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001302 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001303 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001304 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001305
1306 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1307 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001308 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1309 KnownZero2, KnownOne2, Depth+1))
1310 return true;
1311
Dan Gohman23e8b712008-04-28 17:02:21 +00001312 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001313 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001314 KnownZero2, KnownOne2, Depth+1))
1315 return true;
1316
1317 Leaders = std::max(Leaders,
1318 KnownZero2.countLeadingOnes());
1319 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001320 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001321 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001322 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001323
1324 // If the client is only demanding bits that we know, return the known
1325 // constant.
1326 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1327 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1328 return false;
1329}
1330
Chris Lattner867b99f2006-10-05 06:55:50 +00001331
1332/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1333/// 64 or fewer elements. DemandedElts contains the set of elements that are
1334/// actually used by the caller. This method analyzes which elements of the
1335/// operand are undef and returns that information in UndefElts.
1336///
1337/// If the information about demanded elements can be used to simplify the
1338/// operation, the operation is simplified, then the resultant value is
1339/// returned. This returns null if no change was made.
1340Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1341 uint64_t &UndefElts,
1342 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001343 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001344 assert(VWidth <= 64 && "Vector too wide to analyze!");
1345 uint64_t EltMask = ~0ULL >> (64-VWidth);
1346 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1347 "Invalid DemandedElts!");
1348
1349 if (isa<UndefValue>(V)) {
1350 // If the entire vector is undefined, just return this info.
1351 UndefElts = EltMask;
1352 return 0;
1353 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1354 UndefElts = EltMask;
1355 return UndefValue::get(V->getType());
1356 }
1357
1358 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001359 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1360 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001361 Constant *Undef = UndefValue::get(EltTy);
1362
1363 std::vector<Constant*> Elts;
1364 for (unsigned i = 0; i != VWidth; ++i)
1365 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1366 Elts.push_back(Undef);
1367 UndefElts |= (1ULL << i);
1368 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1369 Elts.push_back(Undef);
1370 UndefElts |= (1ULL << i);
1371 } else { // Otherwise, defined.
1372 Elts.push_back(CP->getOperand(i));
1373 }
1374
1375 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001376 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001377 return NewCP != CP ? NewCP : 0;
1378 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001379 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001380 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001381 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001382 Constant *Zero = Constant::getNullValue(EltTy);
1383 Constant *Undef = UndefValue::get(EltTy);
1384 std::vector<Constant*> Elts;
1385 for (unsigned i = 0; i != VWidth; ++i)
1386 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1387 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001388 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001389 }
1390
1391 if (!V->hasOneUse()) { // Other users may use these bits.
1392 if (Depth != 0) { // Not at the root.
1393 // TODO: Just compute the UndefElts information recursively.
1394 return false;
1395 }
1396 return false;
1397 } else if (Depth == 10) { // Limit search depth.
1398 return false;
1399 }
1400
1401 Instruction *I = dyn_cast<Instruction>(V);
1402 if (!I) return false; // Only analyze instructions.
1403
1404 bool MadeChange = false;
1405 uint64_t UndefElts2;
1406 Value *TmpV;
1407 switch (I->getOpcode()) {
1408 default: break;
1409
1410 case Instruction::InsertElement: {
1411 // If this is a variable index, we don't know which element it overwrites.
1412 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001413 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001414 if (Idx == 0) {
1415 // Note that we can't propagate undef elt info, because we don't know
1416 // which elt is getting updated.
1417 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1418 UndefElts2, Depth+1);
1419 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1420 break;
1421 }
1422
1423 // If this is inserting an element that isn't demanded, remove this
1424 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001425 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001426 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1427 return AddSoonDeadInstToWorklist(*I, 0);
1428
1429 // Otherwise, the element inserted overwrites whatever was there, so the
1430 // input demanded set is simpler than the output set.
1431 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1432 DemandedElts & ~(1ULL << IdxNo),
1433 UndefElts, Depth+1);
1434 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1435
1436 // The inserted element is defined.
1437 UndefElts |= 1ULL << IdxNo;
1438 break;
1439 }
Chris Lattner69878332007-04-14 22:29:23 +00001440 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001441 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001442 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1443 if (!VTy) break;
1444 unsigned InVWidth = VTy->getNumElements();
1445 uint64_t InputDemandedElts = 0;
1446 unsigned Ratio;
1447
1448 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001449 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001450 // elements as are demanded of us.
1451 Ratio = 1;
1452 InputDemandedElts = DemandedElts;
1453 } else if (VWidth > InVWidth) {
1454 // Untested so far.
1455 break;
1456
1457 // If there are more elements in the result than there are in the source,
1458 // then an input element is live if any of the corresponding output
1459 // elements are live.
1460 Ratio = VWidth/InVWidth;
1461 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1462 if (DemandedElts & (1ULL << OutIdx))
1463 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1464 }
1465 } else {
1466 // Untested so far.
1467 break;
1468
1469 // If there are more elements in the source than there are in the result,
1470 // then an input element is live if the corresponding output element is
1471 // live.
1472 Ratio = InVWidth/VWidth;
1473 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1474 if (DemandedElts & (1ULL << InIdx/Ratio))
1475 InputDemandedElts |= 1ULL << InIdx;
1476 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001477
Chris Lattner69878332007-04-14 22:29:23 +00001478 // div/rem demand all inputs, because they don't want divide by zero.
1479 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1480 UndefElts2, Depth+1);
1481 if (TmpV) {
1482 I->setOperand(0, TmpV);
1483 MadeChange = true;
1484 }
1485
1486 UndefElts = UndefElts2;
1487 if (VWidth > InVWidth) {
1488 assert(0 && "Unimp");
1489 // If there are more elements in the result than there are in the source,
1490 // then an output element is undef if the corresponding input element is
1491 // undef.
1492 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1493 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1494 UndefElts |= 1ULL << OutIdx;
1495 } else if (VWidth < InVWidth) {
1496 assert(0 && "Unimp");
1497 // If there are more elements in the source than there are in the result,
1498 // then a result element is undef if all of the corresponding input
1499 // elements are undef.
1500 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1501 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1502 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1503 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1504 }
1505 break;
1506 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001507 case Instruction::And:
1508 case Instruction::Or:
1509 case Instruction::Xor:
1510 case Instruction::Add:
1511 case Instruction::Sub:
1512 case Instruction::Mul:
1513 // div/rem demand all inputs, because they don't want divide by zero.
1514 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1515 UndefElts, Depth+1);
1516 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1518 UndefElts2, Depth+1);
1519 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1520
1521 // Output elements are undefined if both are undefined. Consider things
1522 // like undef&0. The result is known zero, not undef.
1523 UndefElts &= UndefElts2;
1524 break;
1525
1526 case Instruction::Call: {
1527 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1528 if (!II) break;
1529 switch (II->getIntrinsicID()) {
1530 default: break;
1531
1532 // Binary vector operations that work column-wise. A dest element is a
1533 // function of the corresponding input elements from the two inputs.
1534 case Intrinsic::x86_sse_sub_ss:
1535 case Intrinsic::x86_sse_mul_ss:
1536 case Intrinsic::x86_sse_min_ss:
1537 case Intrinsic::x86_sse_max_ss:
1538 case Intrinsic::x86_sse2_sub_sd:
1539 case Intrinsic::x86_sse2_mul_sd:
1540 case Intrinsic::x86_sse2_min_sd:
1541 case Intrinsic::x86_sse2_max_sd:
1542 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1543 UndefElts, Depth+1);
1544 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1545 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1546 UndefElts2, Depth+1);
1547 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1548
1549 // If only the low elt is demanded and this is a scalarizable intrinsic,
1550 // scalarize it now.
1551 if (DemandedElts == 1) {
1552 switch (II->getIntrinsicID()) {
1553 default: break;
1554 case Intrinsic::x86_sse_sub_ss:
1555 case Intrinsic::x86_sse_mul_ss:
1556 case Intrinsic::x86_sse2_sub_sd:
1557 case Intrinsic::x86_sse2_mul_sd:
1558 // TODO: Lower MIN/MAX/ABS/etc
1559 Value *LHS = II->getOperand(1);
1560 Value *RHS = II->getOperand(2);
1561 // Extract the element as scalars.
1562 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1563 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1564
1565 switch (II->getIntrinsicID()) {
1566 default: assert(0 && "Case stmts out of sync!");
1567 case Intrinsic::x86_sse_sub_ss:
1568 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001569 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001570 II->getName()), *II);
1571 break;
1572 case Intrinsic::x86_sse_mul_ss:
1573 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001574 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001575 II->getName()), *II);
1576 break;
1577 }
1578
1579 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001580 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1581 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001582 InsertNewInstBefore(New, *II);
1583 AddSoonDeadInstToWorklist(*II, 0);
1584 return New;
1585 }
1586 }
1587
1588 // Output elements are undefined if both are undefined. Consider things
1589 // like undef&0. The result is known zero, not undef.
1590 UndefElts &= UndefElts2;
1591 break;
1592 }
1593 break;
1594 }
1595 }
1596 return MadeChange ? I : 0;
1597}
1598
Dan Gohman45b4e482008-05-19 22:14:15 +00001599
Chris Lattner564a7272003-08-13 19:01:45 +00001600/// AssociativeOpt - Perform an optimization on an associative operator. This
1601/// function is designed to check a chain of associative operators for a
1602/// potential to apply a certain optimization. Since the optimization may be
1603/// applicable if the expression was reassociated, this checks the chain, then
1604/// reassociates the expression as necessary to expose the optimization
1605/// opportunity. This makes use of a special Functor, which must define
1606/// 'shouldApply' and 'apply' methods.
1607///
1608template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001609static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001610 unsigned Opcode = Root.getOpcode();
1611 Value *LHS = Root.getOperand(0);
1612
1613 // Quick check, see if the immediate LHS matches...
1614 if (F.shouldApply(LHS))
1615 return F.apply(Root);
1616
1617 // Otherwise, if the LHS is not of the same opcode as the root, return.
1618 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001619 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001620 // Should we apply this transform to the RHS?
1621 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1622
1623 // If not to the RHS, check to see if we should apply to the LHS...
1624 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1625 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1626 ShouldApply = true;
1627 }
1628
1629 // If the functor wants to apply the optimization to the RHS of LHSI,
1630 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1631 if (ShouldApply) {
1632 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001633
Chris Lattner564a7272003-08-13 19:01:45 +00001634 // Now all of the instructions are in the current basic block, go ahead
1635 // and perform the reassociation.
1636 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1637
1638 // First move the selected RHS to the LHS of the root...
1639 Root.setOperand(0, LHSI->getOperand(1));
1640
1641 // Make what used to be the LHS of the root be the user of the root...
1642 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001643 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001644 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1645 return 0;
1646 }
Chris Lattner65725312004-04-16 18:08:07 +00001647 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001648 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001649 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1650 BasicBlock::iterator ARI = &Root; ++ARI;
1651 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1652 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001653
1654 // Now propagate the ExtraOperand down the chain of instructions until we
1655 // get to LHSI.
1656 while (TmpLHSI != LHSI) {
1657 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001658 // Move the instruction to immediately before the chain we are
1659 // constructing to avoid breaking dominance properties.
1660 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1661 BB->getInstList().insert(ARI, NextLHSI);
1662 ARI = NextLHSI;
1663
Chris Lattner564a7272003-08-13 19:01:45 +00001664 Value *NextOp = NextLHSI->getOperand(1);
1665 NextLHSI->setOperand(1, ExtraOperand);
1666 TmpLHSI = NextLHSI;
1667 ExtraOperand = NextOp;
1668 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001669
Chris Lattner564a7272003-08-13 19:01:45 +00001670 // Now that the instructions are reassociated, have the functor perform
1671 // the transformation...
1672 return F.apply(Root);
1673 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001674
Chris Lattner564a7272003-08-13 19:01:45 +00001675 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1676 }
1677 return 0;
1678}
1679
Dan Gohman844731a2008-05-13 00:00:25 +00001680namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001681
Nick Lewycky02d639f2008-05-23 04:34:58 +00001682// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001683struct AddRHS {
1684 Value *RHS;
1685 AddRHS(Value *rhs) : RHS(rhs) {}
1686 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1687 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001688 return BinaryOperator::CreateShl(Add.getOperand(0),
1689 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001690 }
1691};
1692
1693// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1694// iff C1&C2 == 0
1695struct AddMaskingAnd {
1696 Constant *C2;
1697 AddMaskingAnd(Constant *c) : C2(c) {}
1698 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001699 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001700 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001701 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001702 }
1703 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001704 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001705 }
1706};
1707
Dan Gohman844731a2008-05-13 00:00:25 +00001708}
1709
Chris Lattner6e7ba452005-01-01 16:22:27 +00001710static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001711 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001712 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001713 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001714 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001715
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001716 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00001717 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001718 }
1719
Chris Lattner2eefe512004-04-09 19:05:30 +00001720 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001721 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1722 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001723
Chris Lattner2eefe512004-04-09 19:05:30 +00001724 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1725 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001726 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1727 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001728 }
1729
1730 Value *Op0 = SO, *Op1 = ConstOperand;
1731 if (!ConstIsRHS)
1732 std::swap(Op0, Op1);
1733 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001734 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001735 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001736 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001737 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001738 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001739 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001740 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001741 abort();
1742 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001743 return IC->InsertNewInstBefore(New, I);
1744}
1745
1746// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1747// constant as the other operand, try to fold the binary operator into the
1748// select arguments. This also works for Cast instructions, which obviously do
1749// not have a second operand.
1750static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1751 InstCombiner *IC) {
1752 // Don't modify shared select instructions
1753 if (!SI->hasOneUse()) return 0;
1754 Value *TV = SI->getOperand(1);
1755 Value *FV = SI->getOperand(2);
1756
1757 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001758 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001759 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001760
Chris Lattner6e7ba452005-01-01 16:22:27 +00001761 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1762 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1763
Gabor Greif051a9502008-04-06 20:25:17 +00001764 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1765 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001766 }
1767 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001768}
1769
Chris Lattner4e998b22004-09-29 05:07:12 +00001770
1771/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1772/// node as operand #0, see if we can fold the instruction into the PHI (which
1773/// is only possible if all operands to the PHI are constants).
1774Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1775 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001776 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001777 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001778
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001779 // Check to see if all of the operands of the PHI are constants. If there is
1780 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001781 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001782 BasicBlock *NonConstBB = 0;
1783 for (unsigned i = 0; i != NumPHIValues; ++i)
1784 if (!isa<Constant>(PN->getIncomingValue(i))) {
1785 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001786 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001787 NonConstBB = PN->getIncomingBlock(i);
1788
1789 // If the incoming non-constant value is in I's block, we have an infinite
1790 // loop.
1791 if (NonConstBB == I.getParent())
1792 return 0;
1793 }
1794
1795 // If there is exactly one non-constant value, we can insert a copy of the
1796 // operation in that block. However, if this is a critical edge, we would be
1797 // inserting the computation one some other paths (e.g. inside a loop). Only
1798 // do this if the pred block is unconditionally branching into the phi block.
1799 if (NonConstBB) {
1800 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1801 if (!BI || !BI->isUnconditional()) return 0;
1802 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001803
1804 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001805 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001806 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001807 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001808 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001809
1810 // Next, add all of the operands to the PHI.
1811 if (I.getNumOperands() == 2) {
1812 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001813 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001814 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001815 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001816 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1817 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1818 else
1819 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001820 } else {
1821 assert(PN->getIncomingBlock(i) == NonConstBB);
1822 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001823 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001824 PN->getIncomingValue(i), C, "phitmp",
1825 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001826 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001827 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001828 CI->getPredicate(),
1829 PN->getIncomingValue(i), C, "phitmp",
1830 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001831 else
1832 assert(0 && "Unknown binop!");
1833
Chris Lattnerdbab3862007-03-02 21:28:56 +00001834 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001835 }
1836 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001837 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001838 } else {
1839 CastInst *CI = cast<CastInst>(&I);
1840 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001841 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001842 Value *InV;
1843 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001844 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001845 } else {
1846 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001847 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001848 I.getType(), "phitmp",
1849 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001850 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001851 }
1852 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001853 }
1854 }
1855 return ReplaceInstUsesWith(I, NewPN);
1856}
1857
Chris Lattner2454a2e2008-01-29 06:52:45 +00001858
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001859/// WillNotOverflowSignedAdd - Return true if we can prove that:
1860/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1861/// This basically requires proving that the add in the original type would not
1862/// overflow to change the sign bit or have a carry out.
1863bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1864 // There are different heuristics we can use for this. Here are some simple
1865 // ones.
1866
1867 // Add has the property that adding any two 2's complement numbers can only
1868 // have one carry bit which can change a sign. As such, if LHS and RHS each
1869 // have at least two sign bits, we know that the addition of the two values will
1870 // sign extend fine.
1871 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1872 return true;
1873
1874
1875 // If one of the operands only has one non-zero bit, and if the other operand
1876 // has a known-zero bit in a more significant place than it (not including the
1877 // sign bit) the ripple may go up to and fill the zero, but won't change the
1878 // sign. For example, (X & ~4) + 1.
1879
1880 // TODO: Implement.
1881
1882 return false;
1883}
1884
Chris Lattner2454a2e2008-01-29 06:52:45 +00001885
Chris Lattner7e708292002-06-25 16:13:24 +00001886Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001887 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001888 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001889
Chris Lattner66331a42004-04-10 22:01:55 +00001890 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001891 // X + undef -> undef
1892 if (isa<UndefValue>(RHS))
1893 return ReplaceInstUsesWith(I, RHS);
1894
Chris Lattner66331a42004-04-10 22:01:55 +00001895 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001896 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001897 if (RHSC->isNullValue())
1898 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001899 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001900 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1901 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001902 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001903 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001904
Chris Lattner66331a42004-04-10 22:01:55 +00001905 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001906 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001907 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001908 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001909 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001910 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001911
1912 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1913 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001914 if (!isa<VectorType>(I.getType())) {
1915 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1916 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1917 KnownZero, KnownOne))
1918 return &I;
1919 }
Chris Lattner66331a42004-04-10 22:01:55 +00001920 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001921
1922 if (isa<PHINode>(LHS))
1923 if (Instruction *NV = FoldOpIntoPhi(I))
1924 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001925
Chris Lattner4f637d42006-01-06 17:59:59 +00001926 ConstantInt *XorRHS = 0;
1927 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001928 if (isa<ConstantInt>(RHSC) &&
1929 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00001930 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001931 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00001932
Zhou Sheng4351c642007-04-02 08:20:41 +00001933 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001934 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1935 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00001936 do {
1937 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00001938 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1939 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001940 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1941 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00001942 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00001943 if (!MaskedValueIsZero(XorLHS,
1944 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00001945 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001946 break;
Chris Lattner5931c542005-09-24 23:43:33 +00001947 }
1948 }
1949 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001950 C0080Val = APIntOps::lshr(C0080Val, Size);
1951 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1952 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00001953
Reid Spencer35c38852007-03-28 01:36:16 +00001954 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00001955 // with funny bit widths then this switch statement should be removed. It
1956 // is just here to get the size of the "middle" type back up to something
1957 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00001958 const Type *MiddleType = 0;
1959 switch (Size) {
1960 default: break;
1961 case 32: MiddleType = Type::Int32Ty; break;
1962 case 16: MiddleType = Type::Int16Ty; break;
1963 case 8: MiddleType = Type::Int8Ty; break;
1964 }
1965 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00001966 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00001967 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00001968 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00001969 }
1970 }
Chris Lattner66331a42004-04-10 22:01:55 +00001971 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001972
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001973 if (I.getType() == Type::Int1Ty)
1974 return BinaryOperator::CreateXor(LHS, RHS);
1975
Nick Lewycky7d26bd82008-05-23 04:39:38 +00001976 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001977 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001978 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001979
1980 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1981 if (RHSI->getOpcode() == Instruction::Sub)
1982 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1983 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1984 }
1985 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1986 if (LHSI->getOpcode() == Instruction::Sub)
1987 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1988 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1989 }
Robert Bocchino71698282004-07-27 21:02:21 +00001990 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001991
Chris Lattner5c4afb92002-05-08 22:46:53 +00001992 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00001993 // -A + -B --> -(A + B)
1994 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00001995 if (LHS->getType()->isIntOrIntVector()) {
1996 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001997 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00001998 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001999 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002000 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002001 }
2002
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002003 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002004 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002005
2006 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002007 if (!isa<Constant>(RHS))
2008 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002009 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002010
Misha Brukmanfd939082005-04-21 23:48:37 +00002011
Chris Lattner50af16a2004-11-13 19:50:12 +00002012 ConstantInt *C2;
2013 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2014 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002015 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002016
2017 // X*C1 + X*C2 --> X * (C1+C2)
2018 ConstantInt *C1;
2019 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002020 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002021 }
2022
2023 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002024 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002025 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002026
Chris Lattnere617c9e2007-01-05 02:17:46 +00002027 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002028 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2029 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002030
Chris Lattnerad3448c2003-02-18 19:57:07 +00002031
Chris Lattner564a7272003-08-13 19:01:45 +00002032 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002033 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002034 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2035 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002036
2037 // A+B --> A|B iff A and B have no bits set in common.
2038 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2039 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2040 APInt LHSKnownOne(IT->getBitWidth(), 0);
2041 APInt LHSKnownZero(IT->getBitWidth(), 0);
2042 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2043 if (LHSKnownZero != 0) {
2044 APInt RHSKnownOne(IT->getBitWidth(), 0);
2045 APInt RHSKnownZero(IT->getBitWidth(), 0);
2046 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2047
2048 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002049 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002050 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002051 }
2052 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002053
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002054 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002055 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002056 Value *W, *X, *Y, *Z;
2057 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2058 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2059 if (W != Y) {
2060 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002061 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002062 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002063 std::swap(W, X);
2064 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002065 std::swap(Y, Z);
2066 std::swap(W, X);
2067 }
2068 }
2069
2070 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002071 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002072 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002073 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002074 }
2075 }
2076 }
2077
Chris Lattner6b032052003-10-02 15:11:26 +00002078 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002079 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002080 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002081 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002082
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002083 // (X & FF00) + xx00 -> (X+xx00) & FF00
2084 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002085 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002086 if (Anded == CRHS) {
2087 // See if all bits from the first bit set in the Add RHS up are included
2088 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002089 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002090
2091 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002092 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002093
2094 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002095 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002096
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002097 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2098 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002099 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002100 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002101 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002102 }
2103 }
2104 }
2105
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002106 // Try to fold constant add into select arguments.
2107 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002108 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002109 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002110 }
2111
Reid Spencer1628cec2006-10-26 06:15:43 +00002112 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002113 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002114 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002115 CastInst *CI = dyn_cast<CastInst>(LHS);
2116 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002117 if (!CI) {
2118 CI = dyn_cast<CastInst>(RHS);
2119 Other = LHS;
2120 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002121 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002122 (CI->getType()->getPrimitiveSizeInBits() ==
2123 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002124 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002125 unsigned AS =
2126 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002127 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2128 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002129 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002130 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002131 }
2132 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002133
Chris Lattner42790482007-12-20 01:56:58 +00002134 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002135 {
2136 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2137 Value *Other = RHS;
2138 if (!SI) {
2139 SI = dyn_cast<SelectInst>(RHS);
2140 Other = LHS;
2141 }
Chris Lattner42790482007-12-20 01:56:58 +00002142 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002143 Value *TV = SI->getTrueValue();
2144 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002145 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002146
2147 // Can we fold the add into the argument of the select?
2148 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002149 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2150 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002151 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002152 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2153 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002154 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002155 }
2156 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002157
2158 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2159 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2160 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2161 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002162
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002163 // Check for (add (sext x), y), see if we can merge this into an
2164 // integer add followed by a sext.
2165 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2166 // (add (sext x), cst) --> (sext (add x, cst'))
2167 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2168 Constant *CI =
2169 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2170 if (LHSConv->hasOneUse() &&
2171 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2172 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2173 // Insert the new, smaller add.
2174 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2175 CI, "addconv");
2176 InsertNewInstBefore(NewAdd, I);
2177 return new SExtInst(NewAdd, I.getType());
2178 }
2179 }
2180
2181 // (add (sext x), (sext y)) --> (sext (add int x, y))
2182 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2183 // Only do this if x/y have the same type, if at last one of them has a
2184 // single use (so we don't increase the number of sexts), and if the
2185 // integer add will not overflow.
2186 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2187 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2188 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2189 RHSConv->getOperand(0))) {
2190 // Insert the new integer add.
2191 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2192 RHSConv->getOperand(0),
2193 "addconv");
2194 InsertNewInstBefore(NewAdd, I);
2195 return new SExtInst(NewAdd, I.getType());
2196 }
2197 }
2198 }
2199
2200 // Check for (add double (sitofp x), y), see if we can merge this into an
2201 // integer add followed by a promotion.
2202 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2203 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2204 // ... if the constant fits in the integer value. This is useful for things
2205 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2206 // requires a constant pool load, and generally allows the add to be better
2207 // instcombined.
2208 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2209 Constant *CI =
2210 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2211 if (LHSConv->hasOneUse() &&
2212 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2213 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2214 // Insert the new integer add.
2215 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2216 CI, "addconv");
2217 InsertNewInstBefore(NewAdd, I);
2218 return new SIToFPInst(NewAdd, I.getType());
2219 }
2220 }
2221
2222 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2223 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2224 // Only do this if x/y have the same type, if at last one of them has a
2225 // single use (so we don't increase the number of int->fp conversions),
2226 // and if the integer add will not overflow.
2227 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2228 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2229 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2230 RHSConv->getOperand(0))) {
2231 // Insert the new integer add.
2232 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2233 RHSConv->getOperand(0),
2234 "addconv");
2235 InsertNewInstBefore(NewAdd, I);
2236 return new SIToFPInst(NewAdd, I.getType());
2237 }
2238 }
2239 }
2240
Chris Lattner7e708292002-06-25 16:13:24 +00002241 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002242}
2243
Chris Lattner7e708292002-06-25 16:13:24 +00002244Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002245 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002246
Chris Lattner233f7dc2002-08-12 21:17:25 +00002247 if (Op0 == Op1) // sub X, X -> 0
2248 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002249
Chris Lattner233f7dc2002-08-12 21:17:25 +00002250 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002251 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002252 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002253
Chris Lattnere87597f2004-10-16 18:11:37 +00002254 if (isa<UndefValue>(Op0))
2255 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2256 if (isa<UndefValue>(Op1))
2257 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2258
Chris Lattnerd65460f2003-11-05 01:06:05 +00002259 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2260 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002261 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002262 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002263
Chris Lattnerd65460f2003-11-05 01:06:05 +00002264 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002265 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002266 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002267 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002268
Chris Lattner76b7a062007-01-15 07:02:54 +00002269 // -(X >>u 31) -> (X >>s 31)
2270 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002271 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002272 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002273 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002274 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002275 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002276 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002277 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002278 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002279 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002280 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002281 }
2282 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002283 }
2284 else if (SI->getOpcode() == Instruction::AShr) {
2285 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2286 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002287 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002288 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002289 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002290 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002291 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002292 }
2293 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002294 }
2295 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002296 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002297
2298 // Try to fold constant sub into select arguments.
2299 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002300 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002301 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002302
2303 if (isa<PHINode>(Op0))
2304 if (Instruction *NV = FoldOpIntoPhi(I))
2305 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002306 }
2307
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002308 if (I.getType() == Type::Int1Ty)
2309 return BinaryOperator::CreateXor(Op0, Op1);
2310
Chris Lattner43d84d62005-04-07 16:15:25 +00002311 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2312 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002313 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002314 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002315 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002316 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002317 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002318 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2319 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2320 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002321 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002322 Op1I->getOperand(0));
2323 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002324 }
2325
Chris Lattnerfd059242003-10-15 16:48:29 +00002326 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002327 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2328 // is not used by anyone else...
2329 //
Chris Lattner0517e722004-02-02 20:09:56 +00002330 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002331 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002332 // Swap the two operands of the subexpr...
2333 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2334 Op1I->setOperand(0, IIOp1);
2335 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002336
Chris Lattnera2881962003-02-18 19:28:33 +00002337 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002338 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002339 }
2340
2341 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2342 //
2343 if (Op1I->getOpcode() == Instruction::And &&
2344 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2345 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2346
Chris Lattnerf523d062004-06-09 05:08:07 +00002347 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002348 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2349 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002350 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002351
Reid Spencerac5209e2006-10-16 23:08:08 +00002352 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002353 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002354 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002355 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002356 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002357 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002358 ConstantExpr::getNeg(DivRHS));
2359
Chris Lattnerad3448c2003-02-18 19:57:07 +00002360 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002361 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002362 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002363 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002364 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002365 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002366
2367 // X - ((X / Y) * Y) --> X % Y
2368 if (Op1I->getOpcode() == Instruction::Mul)
2369 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2370 if (Op0 == I->getOperand(0) &&
2371 Op1I->getOperand(1) == I->getOperand(1)) {
2372 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002373 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002374 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002375 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002376 }
Chris Lattner40371712002-05-09 01:29:19 +00002377 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002378 }
Chris Lattnera2881962003-02-18 19:28:33 +00002379
Chris Lattner9919e3d2006-12-02 00:13:08 +00002380 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002381 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002382 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002383 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2384 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2385 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2386 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002387 } else if (Op0I->getOpcode() == Instruction::Sub) {
2388 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002389 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002390 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002391 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002392
Chris Lattner50af16a2004-11-13 19:50:12 +00002393 ConstantInt *C1;
2394 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002395 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002396 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002397
Chris Lattner50af16a2004-11-13 19:50:12 +00002398 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2399 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002400 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002401 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002402 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002403}
2404
Chris Lattnera0141b92007-07-15 20:42:37 +00002405/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2406/// comparison only checks the sign bit. If it only checks the sign bit, set
2407/// TrueIfSigned if the result of the comparison is true when the input value is
2408/// signed.
2409static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2410 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002411 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002412 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2413 TrueIfSigned = true;
2414 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002415 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2416 TrueIfSigned = true;
2417 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002418 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2419 TrueIfSigned = false;
2420 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002421 case ICmpInst::ICMP_UGT:
2422 // True if LHS u> RHS and RHS == high-bit-mask - 1
2423 TrueIfSigned = true;
2424 return RHS->getValue() ==
2425 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2426 case ICmpInst::ICMP_UGE:
2427 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2428 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002429 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002430 default:
2431 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002432 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002433}
2434
Chris Lattner7e708292002-06-25 16:13:24 +00002435Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002436 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002437 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002438
Chris Lattnere87597f2004-10-16 18:11:37 +00002439 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2440 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2441
Chris Lattner233f7dc2002-08-12 21:17:25 +00002442 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002443 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2444 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002445
2446 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002447 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002448 if (SI->getOpcode() == Instruction::Shl)
2449 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002450 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002451 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002452
Zhou Sheng843f07672007-04-19 05:39:12 +00002453 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002454 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2455 if (CI->equalsInt(1)) // X * 1 == X
2456 return ReplaceInstUsesWith(I, Op0);
2457 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002458 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002459
Zhou Sheng97b52c22007-03-29 01:57:21 +00002460 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002461 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002462 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002463 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002464 }
Robert Bocchino71698282004-07-27 21:02:21 +00002465 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002466 if (Op1F->isNullValue())
2467 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002468
Chris Lattnera2881962003-02-18 19:28:33 +00002469 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2470 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002471 // We need a better interface for long double here.
2472 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2473 if (Op1F->isExactlyValue(1.0))
2474 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002475 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002476
2477 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2478 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002479 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002480 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002481 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002482 Op1, "tmp");
2483 InsertNewInstBefore(Add, I);
2484 Value *C1C2 = ConstantExpr::getMul(Op1,
2485 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002486 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002487
2488 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002489
2490 // Try to fold constant mul into select arguments.
2491 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002492 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002493 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002494
2495 if (isa<PHINode>(Op0))
2496 if (Instruction *NV = FoldOpIntoPhi(I))
2497 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002498 }
2499
Chris Lattnera4f445b2003-03-10 23:23:04 +00002500 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2501 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002502 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002503
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002504 if (I.getType() == Type::Int1Ty)
2505 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2506
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002507 // If one of the operands of the multiply is a cast from a boolean value, then
2508 // we know the bool is either zero or one, so this is a 'masking' multiply.
2509 // See if we can simplify things based on how the boolean was originally
2510 // formed.
2511 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002512 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002513 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002514 BoolCast = CI;
2515 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002516 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002517 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002518 BoolCast = CI;
2519 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002520 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002521 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2522 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002523 bool TIS = false;
2524
Reid Spencere4d87aa2006-12-23 06:05:41 +00002525 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002526 // multiply into a shift/and combination.
2527 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002528 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2529 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002530 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002531 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002532 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002533 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002534 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002535 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002536 BoolCast->getOperand(0)->getName()+
2537 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002538
2539 // If the multiply type is not the same as the source type, sign extend
2540 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002541 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002542 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2543 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002544 Instruction::CastOps opcode =
2545 (SrcBits == DstBits ? Instruction::BitCast :
2546 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2547 V = InsertCastBefore(opcode, V, I.getType(), I);
2548 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002549
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002550 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002551 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002552 }
2553 }
2554 }
2555
Chris Lattner7e708292002-06-25 16:13:24 +00002556 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002557}
2558
Reid Spencer1628cec2006-10-26 06:15:43 +00002559/// This function implements the transforms on div instructions that work
2560/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2561/// used by the visitors to those instructions.
2562/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002563Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002564 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002565
Chris Lattner50b2ca42008-02-19 06:12:18 +00002566 // undef / X -> 0 for integer.
2567 // undef / X -> undef for FP (the undef could be a snan).
2568 if (isa<UndefValue>(Op0)) {
2569 if (Op0->getType()->isFPOrFPVector())
2570 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002571 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002572 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002573
2574 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002575 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002576 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002577
Chris Lattner25feae52008-01-28 00:58:18 +00002578 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2579 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002580 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002581 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2582 // the same basic block, then we replace the select with Y, and the
2583 // condition of the select with false (if the cond value is in the same BB).
2584 // If the select has uses other than the div, this allows them to be
2585 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2586 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002587 if (ST->isNullValue()) {
2588 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2589 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002590 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002591 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2592 I.setOperand(1, SI->getOperand(2));
2593 else
2594 UpdateValueUsesWith(SI, SI->getOperand(2));
2595 return &I;
2596 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002597
Chris Lattner25feae52008-01-28 00:58:18 +00002598 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2599 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002600 if (ST->isNullValue()) {
2601 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2602 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002603 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002604 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2605 I.setOperand(1, SI->getOperand(1));
2606 else
2607 UpdateValueUsesWith(SI, SI->getOperand(1));
2608 return &I;
2609 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002610 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002611
Reid Spencer1628cec2006-10-26 06:15:43 +00002612 return 0;
2613}
Misha Brukmanfd939082005-04-21 23:48:37 +00002614
Reid Spencer1628cec2006-10-26 06:15:43 +00002615/// This function implements the transforms common to both integer division
2616/// instructions (udiv and sdiv). It is called by the visitors to those integer
2617/// division instructions.
2618/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002619Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002620 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2621
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002622 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002623 if (Op0 == Op1) {
2624 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2625 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2626 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2627 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2628 }
2629
2630 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2631 return ReplaceInstUsesWith(I, CI);
2632 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002633
Reid Spencer1628cec2006-10-26 06:15:43 +00002634 if (Instruction *Common = commonDivTransforms(I))
2635 return Common;
2636
2637 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2638 // div X, 1 == X
2639 if (RHS->equalsInt(1))
2640 return ReplaceInstUsesWith(I, Op0);
2641
2642 // (X / C1) / C2 -> X / (C1*C2)
2643 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2644 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2645 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002646 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2647 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2648 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002649 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002650 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002651 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002652
Reid Spencerbca0e382007-03-23 20:05:17 +00002653 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002654 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2655 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2656 return R;
2657 if (isa<PHINode>(Op0))
2658 if (Instruction *NV = FoldOpIntoPhi(I))
2659 return NV;
2660 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002661 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002662
Chris Lattnera2881962003-02-18 19:28:33 +00002663 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002664 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002665 if (LHS->equalsInt(0))
2666 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2667
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002668 // It can't be division by zero, hence it must be division by one.
2669 if (I.getType() == Type::Int1Ty)
2670 return ReplaceInstUsesWith(I, Op0);
2671
Reid Spencer1628cec2006-10-26 06:15:43 +00002672 return 0;
2673}
2674
2675Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2676 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2677
2678 // Handle the integer div common cases
2679 if (Instruction *Common = commonIDivTransforms(I))
2680 return Common;
2681
2682 // X udiv C^2 -> X >> C
2683 // Check to see if this is an unsigned division with an exact power of 2,
2684 // if so, convert to a right shift.
2685 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002686 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002687 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002688 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002689 }
2690
2691 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002692 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002693 if (RHSI->getOpcode() == Instruction::Shl &&
2694 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002695 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002696 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002697 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002698 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002699 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002700 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002701 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002702 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002703 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002704 }
2705 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002706 }
2707
Reid Spencer1628cec2006-10-26 06:15:43 +00002708 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2709 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002710 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002711 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002712 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002713 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002714 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002715 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002716 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002717 // Construct the "on true" case of the select
2718 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002719 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002720 Op0, TC, SI->getName()+".t");
2721 TSI = InsertNewInstBefore(TSI, I);
2722
2723 // Construct the "on false" case of the select
2724 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002725 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002726 Op0, FC, SI->getName()+".f");
2727 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002728
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002729 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002730 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002731 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002732 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002733 return 0;
2734}
2735
Reid Spencer1628cec2006-10-26 06:15:43 +00002736Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2737 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2738
2739 // Handle the integer div common cases
2740 if (Instruction *Common = commonIDivTransforms(I))
2741 return Common;
2742
2743 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2744 // sdiv X, -1 == -X
2745 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002746 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002747
2748 // -X/C -> X/-C
2749 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002750 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00002751 }
2752
2753 // If the sign bits of both operands are zero (i.e. we can prove they are
2754 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002755 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002756 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002757 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002758 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002759 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002760 }
2761 }
2762
2763 return 0;
2764}
2765
2766Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2767 return commonDivTransforms(I);
2768}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002769
Reid Spencer0a783f72006-11-02 01:53:59 +00002770/// This function implements the transforms on rem instructions that work
2771/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2772/// is used by the visitors to those instructions.
2773/// @brief Transforms common to all three rem instructions
2774Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002775 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002776
Chris Lattner50b2ca42008-02-19 06:12:18 +00002777 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002778 if (Constant *LHS = dyn_cast<Constant>(Op0))
2779 if (LHS->isNullValue())
2780 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2781
Chris Lattner50b2ca42008-02-19 06:12:18 +00002782 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2783 if (I.getType()->isFPOrFPVector())
2784 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002785 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002786 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002787 if (isa<UndefValue>(Op1))
2788 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002789
2790 // Handle cases involving: rem X, (select Cond, Y, Z)
2791 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2792 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2793 // the same basic block, then we replace the select with Y, and the
2794 // condition of the select with false (if the cond value is in the same
2795 // BB). If the select has uses other than the div, this allows them to be
2796 // simplified also.
2797 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2798 if (ST->isNullValue()) {
2799 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2800 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002801 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002802 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2803 I.setOperand(1, SI->getOperand(2));
2804 else
2805 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002806 return &I;
2807 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002808 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2809 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2810 if (ST->isNullValue()) {
2811 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2812 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002813 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002814 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2815 I.setOperand(1, SI->getOperand(1));
2816 else
2817 UpdateValueUsesWith(SI, SI->getOperand(1));
2818 return &I;
2819 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002820 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002821
Reid Spencer0a783f72006-11-02 01:53:59 +00002822 return 0;
2823}
2824
2825/// This function implements the transforms common to both integer remainder
2826/// instructions (urem and srem). It is called by the visitors to those integer
2827/// remainder instructions.
2828/// @brief Common integer remainder transforms
2829Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2830 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2831
2832 if (Instruction *common = commonRemTransforms(I))
2833 return common;
2834
Chris Lattner857e8cd2004-12-12 21:48:58 +00002835 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002836 // X % 0 == undef, we don't need to preserve faults!
2837 if (RHS->equalsInt(0))
2838 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2839
Chris Lattnera2881962003-02-18 19:28:33 +00002840 if (RHS->equalsInt(1)) // X % 1 == 0
2841 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2842
Chris Lattner97943922006-02-28 05:49:21 +00002843 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2844 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2845 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2846 return R;
2847 } else if (isa<PHINode>(Op0I)) {
2848 if (Instruction *NV = FoldOpIntoPhi(I))
2849 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002850 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002851
2852 // See if we can fold away this rem instruction.
2853 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2854 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2855 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2856 KnownZero, KnownOne))
2857 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002858 }
Chris Lattnera2881962003-02-18 19:28:33 +00002859 }
2860
Reid Spencer0a783f72006-11-02 01:53:59 +00002861 return 0;
2862}
2863
2864Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2865 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2866
2867 if (Instruction *common = commonIRemTransforms(I))
2868 return common;
2869
2870 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2871 // X urem C^2 -> X and C
2872 // Check to see if this is an unsigned remainder with an exact power of 2,
2873 // if so, convert to a bitwise and.
2874 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002875 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002876 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00002877 }
2878
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002879 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002880 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2881 if (RHSI->getOpcode() == Instruction::Shl &&
2882 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002883 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002884 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002885 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002886 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002887 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002888 }
2889 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002890 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002891
Reid Spencer0a783f72006-11-02 01:53:59 +00002892 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2893 // where C1&C2 are powers of two.
2894 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2895 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2896 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2897 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002898 if ((STO->getValue().isPowerOf2()) &&
2899 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002900 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002901 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00002902 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002903 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002904 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00002905 }
2906 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002907 }
2908
Chris Lattner3f5b8772002-05-06 16:14:14 +00002909 return 0;
2910}
2911
Reid Spencer0a783f72006-11-02 01:53:59 +00002912Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2913 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2914
Dan Gohmancff55092007-11-05 23:16:33 +00002915 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002916 if (Instruction *common = commonIRemTransforms(I))
2917 return common;
2918
2919 if (Value *RHSNeg = dyn_castNegVal(Op1))
2920 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002921 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002922 // X % -Y -> X % Y
2923 AddUsesToWorkList(I);
2924 I.setOperand(1, RHSNeg);
2925 return &I;
2926 }
2927
Dan Gohmancff55092007-11-05 23:16:33 +00002928 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002929 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002930 if (I.getType()->isInteger()) {
2931 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2932 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2933 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002934 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00002935 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002936 }
2937
2938 return 0;
2939}
2940
2941Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002942 return commonRemTransforms(I);
2943}
2944
Chris Lattner8b170942002-08-09 23:47:40 +00002945// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002946static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002947 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00002948 if (!isSigned)
2949 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2950 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002951}
2952
2953// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002954static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002955 if (!isSigned)
2956 return C->getValue() == 1; // unsigned
2957
2958 // Calculate 1111111111000000000000
2959 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2960 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002961}
2962
Chris Lattner457dd822004-06-09 07:59:58 +00002963// isOneBitSet - Return true if there is exactly one bit set in the specified
2964// constant.
2965static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002966 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002967}
2968
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002969// isHighOnes - Return true if the constant is of the form 1+0+.
2970// This is the same as lowones(~X).
2971static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002972 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002973}
2974
Reid Spencere4d87aa2006-12-23 06:05:41 +00002975/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002976/// are carefully arranged to allow folding of expressions such as:
2977///
2978/// (A < B) | (A > B) --> (A != B)
2979///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002980/// Note that this is only valid if the first and second predicates have the
2981/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002982///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002983/// Three bits are used to represent the condition, as follows:
2984/// 0 A > B
2985/// 1 A == B
2986/// 2 A < B
2987///
2988/// <=> Value Definition
2989/// 000 0 Always false
2990/// 001 1 A > B
2991/// 010 2 A == B
2992/// 011 3 A >= B
2993/// 100 4 A < B
2994/// 101 5 A != B
2995/// 110 6 A <= B
2996/// 111 7 Always true
2997///
2998static unsigned getICmpCode(const ICmpInst *ICI) {
2999 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003000 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003001 case ICmpInst::ICMP_UGT: return 1; // 001
3002 case ICmpInst::ICMP_SGT: return 1; // 001
3003 case ICmpInst::ICMP_EQ: return 2; // 010
3004 case ICmpInst::ICMP_UGE: return 3; // 011
3005 case ICmpInst::ICMP_SGE: return 3; // 011
3006 case ICmpInst::ICMP_ULT: return 4; // 100
3007 case ICmpInst::ICMP_SLT: return 4; // 100
3008 case ICmpInst::ICMP_NE: return 5; // 101
3009 case ICmpInst::ICMP_ULE: return 6; // 110
3010 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003011 // True -> 7
3012 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003013 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003014 return 0;
3015 }
3016}
3017
Reid Spencere4d87aa2006-12-23 06:05:41 +00003018/// getICmpValue - This is the complement of getICmpCode, which turns an
3019/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003020/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003021/// of predicate to use in new icmp instructions.
3022static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3023 switch (code) {
3024 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003025 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003026 case 1:
3027 if (sign)
3028 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3029 else
3030 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3031 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3032 case 3:
3033 if (sign)
3034 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3035 else
3036 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3037 case 4:
3038 if (sign)
3039 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3040 else
3041 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3042 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3043 case 6:
3044 if (sign)
3045 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3046 else
3047 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003048 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003049 }
3050}
3051
Reid Spencere4d87aa2006-12-23 06:05:41 +00003052static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3053 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3054 (ICmpInst::isSignedPredicate(p1) &&
3055 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3056 (ICmpInst::isSignedPredicate(p2) &&
3057 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3058}
3059
3060namespace {
3061// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3062struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003063 InstCombiner &IC;
3064 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003065 ICmpInst::Predicate pred;
3066 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3067 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3068 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003069 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003070 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3071 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003072 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3073 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003074 return false;
3075 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003076 Instruction *apply(Instruction &Log) const {
3077 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3078 if (ICI->getOperand(0) != LHS) {
3079 assert(ICI->getOperand(1) == LHS);
3080 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003081 }
3082
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003083 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003084 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003085 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003086 unsigned Code;
3087 switch (Log.getOpcode()) {
3088 case Instruction::And: Code = LHSCode & RHSCode; break;
3089 case Instruction::Or: Code = LHSCode | RHSCode; break;
3090 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003091 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003092 }
3093
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003094 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3095 ICmpInst::isSignedPredicate(ICI->getPredicate());
3096
3097 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003098 if (Instruction *I = dyn_cast<Instruction>(RV))
3099 return I;
3100 // Otherwise, it's a constant boolean value...
3101 return IC.ReplaceInstUsesWith(Log, RV);
3102 }
3103};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003104} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003105
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003106// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3107// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003108// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003109Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003110 ConstantInt *OpRHS,
3111 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003112 BinaryOperator &TheAnd) {
3113 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003114 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003115 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003116 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003117
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003118 switch (Op->getOpcode()) {
3119 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003120 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003121 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003122 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003123 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003124 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003125 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003126 }
3127 break;
3128 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003129 if (Together == AndRHS) // (X | C) & C --> C
3130 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003131
Chris Lattner6e7ba452005-01-01 16:22:27 +00003132 if (Op->hasOneUse() && Together != OpRHS) {
3133 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003134 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003135 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003136 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003137 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003138 }
3139 break;
3140 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003141 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003142 // Adding a one to a single bit bit-field should be turned into an XOR
3143 // of the bit. First thing to check is to see if this AND is with a
3144 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003145 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003146
3147 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003148 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003149 // Ok, at this point, we know that we are masking the result of the
3150 // ADD down to exactly one bit. If the constant we are adding has
3151 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003152 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003153
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003154 // Check to see if any bits below the one bit set in AndRHSV are set.
3155 if ((AddRHS & (AndRHSV-1)) == 0) {
3156 // If not, the only thing that can effect the output of the AND is
3157 // the bit specified by AndRHSV. If that bit is set, the effect of
3158 // the XOR is to toggle the bit. If it is clear, then the ADD has
3159 // no effect.
3160 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3161 TheAnd.setOperand(0, X);
3162 return &TheAnd;
3163 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003164 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003165 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003166 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003167 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003168 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003169 }
3170 }
3171 }
3172 }
3173 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003174
3175 case Instruction::Shl: {
3176 // We know that the AND will not produce any of the bits shifted in, so if
3177 // the anded constant includes them, clear them now!
3178 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003179 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003180 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003181 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3182 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003183
Zhou Sheng290bec52007-03-29 08:15:12 +00003184 if (CI->getValue() == ShlMask) {
3185 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003186 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3187 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003188 TheAnd.setOperand(1, CI);
3189 return &TheAnd;
3190 }
3191 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003192 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003193 case Instruction::LShr:
3194 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003195 // We know that the AND will not produce any of the bits shifted in, so if
3196 // the anded constant includes them, clear them now! This only applies to
3197 // unsigned shifts, because a signed shr may bring in set bits!
3198 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003199 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003200 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003201 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3202 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003203
Zhou Sheng290bec52007-03-29 08:15:12 +00003204 if (CI->getValue() == ShrMask) {
3205 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003206 return ReplaceInstUsesWith(TheAnd, Op);
3207 } else if (CI != AndRHS) {
3208 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3209 return &TheAnd;
3210 }
3211 break;
3212 }
3213 case Instruction::AShr:
3214 // Signed shr.
3215 // See if this is shifting in some sign extension, then masking it out
3216 // with an and.
3217 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003218 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003219 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003220 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3221 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003222 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003223 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003224 // Make the argument unsigned.
3225 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003226 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003227 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003228 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003229 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003230 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003231 }
3232 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003233 }
3234 return 0;
3235}
3236
Chris Lattner8b170942002-08-09 23:47:40 +00003237
Chris Lattnera96879a2004-09-29 17:40:11 +00003238/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3239/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003240/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3241/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003242/// insert new instructions.
3243Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003244 bool isSigned, bool Inside,
3245 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003246 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003247 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003248 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003249
Chris Lattnera96879a2004-09-29 17:40:11 +00003250 if (Inside) {
3251 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003252 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003253
Reid Spencere4d87aa2006-12-23 06:05:41 +00003254 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003255 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003256 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003257 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3258 return new ICmpInst(pred, V, Hi);
3259 }
3260
3261 // Emit V-Lo <u Hi-Lo
3262 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003263 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003264 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003265 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3266 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003267 }
3268
3269 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003270 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003271
Reid Spencere4e40032007-03-21 23:19:50 +00003272 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003273 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003274 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003275 ICmpInst::Predicate pred = (isSigned ?
3276 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3277 return new ICmpInst(pred, V, Hi);
3278 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003279
Reid Spencere4e40032007-03-21 23:19:50 +00003280 // Emit V-Lo >u Hi-1-Lo
3281 // Note that Hi has already had one subtracted from it, above.
3282 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003283 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003284 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003285 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3286 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003287}
3288
Chris Lattner7203e152005-09-18 07:22:02 +00003289// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3290// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3291// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3292// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003293static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003294 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003295 uint32_t BitWidth = Val->getType()->getBitWidth();
3296 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003297
3298 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003299 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003300 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003301 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003302 return true;
3303}
3304
Chris Lattner7203e152005-09-18 07:22:02 +00003305/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3306/// where isSub determines whether the operator is a sub. If we can fold one of
3307/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003308///
3309/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3310/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3311/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3312///
3313/// return (A +/- B).
3314///
3315Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003316 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003317 Instruction &I) {
3318 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3319 if (!LHSI || LHSI->getNumOperands() != 2 ||
3320 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3321
3322 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3323
3324 switch (LHSI->getOpcode()) {
3325 default: return 0;
3326 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003327 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003328 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003329 if ((Mask->getValue().countLeadingZeros() +
3330 Mask->getValue().countPopulation()) ==
3331 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003332 break;
3333
3334 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3335 // part, we don't need any explicit masks to take them out of A. If that
3336 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003337 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003338 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003339 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003340 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003341 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003342 break;
3343 }
3344 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003345 return 0;
3346 case Instruction::Or:
3347 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003348 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003349 if ((Mask->getValue().countLeadingZeros() +
3350 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003351 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003352 break;
3353 return 0;
3354 }
3355
3356 Instruction *New;
3357 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003358 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003359 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003360 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003361 return InsertNewInstBefore(New, I);
3362}
3363
Chris Lattner7e708292002-06-25 16:13:24 +00003364Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003365 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003366 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003367
Chris Lattnere87597f2004-10-16 18:11:37 +00003368 if (isa<UndefValue>(Op1)) // X & undef -> 0
3369 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3370
Chris Lattner6e7ba452005-01-01 16:22:27 +00003371 // and X, X = X
3372 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003373 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003374
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003375 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003376 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003377 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003378 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3379 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3380 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003381 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003382 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003383 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003384 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003385 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003386 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003387 } else if (isa<ConstantAggregateZero>(Op1)) {
3388 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003389 }
3390 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003391
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003392 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003393 const APInt& AndRHSMask = AndRHS->getValue();
3394 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003395
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003396 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003397 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003398 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003399 Value *Op0LHS = Op0I->getOperand(0);
3400 Value *Op0RHS = Op0I->getOperand(1);
3401 switch (Op0I->getOpcode()) {
3402 case Instruction::Xor:
3403 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003404 // If the mask is only needed on one incoming arm, push it up.
3405 if (Op0I->hasOneUse()) {
3406 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3407 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003408 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003409 Op0RHS->getName()+".masked");
3410 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003411 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003412 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003413 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003414 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003415 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3416 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003417 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003418 Op0LHS->getName()+".masked");
3419 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003420 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003421 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3422 }
3423 }
3424
Chris Lattner6e7ba452005-01-01 16:22:27 +00003425 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003426 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003427 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3428 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3429 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3430 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003431 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003432 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003433 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003434 break;
3435
3436 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003437 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3438 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3439 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3440 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003441 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003442 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003443 }
3444
Chris Lattner58403262003-07-23 19:25:52 +00003445 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003446 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003447 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003448 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003449 // If this is an integer truncation or change from signed-to-unsigned, and
3450 // if the source is an and/or with immediate, transform it. This
3451 // frequently occurs for bitfield accesses.
3452 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003453 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003454 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003455 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003456 if (CastOp->getOpcode() == Instruction::And) {
3457 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003458 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3459 // This will fold the two constants together, which may allow
3460 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003461 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003462 CastOp->getOperand(0), I.getType(),
3463 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003464 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003465 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003466 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003467 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003468 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003469 } else if (CastOp->getOpcode() == Instruction::Or) {
3470 // Change: and (cast (or X, C1) to T), C2
3471 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003472 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003473 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3474 return ReplaceInstUsesWith(I, AndRHS);
3475 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003476 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003477 }
Chris Lattner06782f82003-07-23 19:36:21 +00003478 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003479
3480 // Try to fold constant and into select arguments.
3481 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003482 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003483 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003484 if (isa<PHINode>(Op0))
3485 if (Instruction *NV = FoldOpIntoPhi(I))
3486 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003487 }
3488
Chris Lattner8d969642003-03-10 23:06:50 +00003489 Value *Op0NotVal = dyn_castNotVal(Op0);
3490 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003491
Chris Lattner5b62aa72004-06-18 06:07:51 +00003492 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3493 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3494
Misha Brukmancb6267b2004-07-30 12:50:08 +00003495 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003496 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003497 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003498 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003499 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003500 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003501 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003502
3503 {
Chris Lattner003b6202007-06-15 05:58:24 +00003504 Value *A = 0, *B = 0, *C = 0, *D = 0;
3505 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003506 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3507 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003508
3509 // (A|B) & ~(A&B) -> A^B
3510 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3511 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003512 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003513 }
3514 }
3515
3516 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003517 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3518 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003519
3520 // ~(A&B) & (A|B) -> A^B
3521 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3522 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003523 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003524 }
3525 }
Chris Lattner64daab52006-04-01 08:03:55 +00003526
3527 if (Op0->hasOneUse() &&
3528 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3529 if (A == Op1) { // (A^B)&A -> A&(A^B)
3530 I.swapOperands(); // Simplify below
3531 std::swap(Op0, Op1);
3532 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3533 cast<BinaryOperator>(Op0)->swapOperands();
3534 I.swapOperands(); // Simplify below
3535 std::swap(Op0, Op1);
3536 }
3537 }
3538 if (Op1->hasOneUse() &&
3539 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3540 if (B == Op0) { // B&(A^B) -> B&(B^A)
3541 cast<BinaryOperator>(Op1)->swapOperands();
3542 std::swap(A, B);
3543 }
3544 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003545 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003546 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003547 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003548 }
3549 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003550 }
3551
Reid Spencere4d87aa2006-12-23 06:05:41 +00003552 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3553 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3554 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003555 return R;
3556
Chris Lattner955f3312004-09-28 21:48:02 +00003557 Value *LHSVal, *RHSVal;
3558 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003559 ICmpInst::Predicate LHSCC, RHSCC;
3560 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3561 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3562 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3563 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3564 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3565 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3566 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003567 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3568
3569 // Don't try to fold ICMP_SLT + ICMP_ULT.
3570 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3571 ICmpInst::isSignedPredicate(LHSCC) ==
3572 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003573 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003574 ICmpInst::Predicate GT;
3575 if (ICmpInst::isSignedPredicate(LHSCC) ||
3576 (ICmpInst::isEquality(LHSCC) &&
3577 ICmpInst::isSignedPredicate(RHSCC)))
3578 GT = ICmpInst::ICMP_SGT;
3579 else
3580 GT = ICmpInst::ICMP_UGT;
3581
Reid Spencere4d87aa2006-12-23 06:05:41 +00003582 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3583 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003584 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003585 std::swap(LHS, RHS);
3586 std::swap(LHSCst, RHSCst);
3587 std::swap(LHSCC, RHSCC);
3588 }
3589
Reid Spencere4d87aa2006-12-23 06:05:41 +00003590 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003591 // comparing a value against two constants and and'ing the result
3592 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003593 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3594 // (from the FoldICmpLogical check above), that the two constants
3595 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003596 assert(LHSCst != RHSCst && "Compares not folded above?");
3597
3598 switch (LHSCC) {
3599 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003600 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003601 switch (RHSCC) {
3602 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003603 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3604 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3605 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003606 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003607 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3608 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3609 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003610 return ReplaceInstUsesWith(I, LHS);
3611 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003612 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003613 switch (RHSCC) {
3614 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003615 case ICmpInst::ICMP_ULT:
3616 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3617 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3618 break; // (X != 13 & X u< 15) -> no change
3619 case ICmpInst::ICMP_SLT:
3620 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3621 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3622 break; // (X != 13 & X s< 15) -> no change
3623 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3624 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3625 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003626 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003627 case ICmpInst::ICMP_NE:
3628 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003629 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003630 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00003631 LHSVal->getName()+".off");
3632 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003633 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3634 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003635 }
3636 break; // (X != 13 & X != 15) -> no change
3637 }
3638 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003640 switch (RHSCC) {
3641 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003642 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3643 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003644 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003645 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3646 break;
3647 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3648 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003649 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003650 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3651 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003652 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653 break;
3654 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003655 switch (RHSCC) {
3656 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003657 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3658 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003659 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003660 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3661 break;
3662 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3663 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003664 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003665 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3666 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003667 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003668 break;
3669 case ICmpInst::ICMP_UGT:
3670 switch (RHSCC) {
3671 default: assert(0 && "Unknown integer condition code!");
3672 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3673 return ReplaceInstUsesWith(I, LHS);
3674 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3675 return ReplaceInstUsesWith(I, RHS);
3676 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3677 break;
3678 case ICmpInst::ICMP_NE:
3679 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3680 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3681 break; // (X u> 13 & X != 15) -> no change
3682 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3683 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3684 true, I);
3685 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3686 break;
3687 }
3688 break;
3689 case ICmpInst::ICMP_SGT:
3690 switch (RHSCC) {
3691 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003692 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003693 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3694 return ReplaceInstUsesWith(I, RHS);
3695 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3696 break;
3697 case ICmpInst::ICMP_NE:
3698 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3699 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3700 break; // (X s> 13 & X != 15) -> no change
3701 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3702 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3703 true, I);
3704 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3705 break;
3706 }
3707 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003708 }
3709 }
3710 }
3711
Chris Lattner6fc205f2006-05-05 06:39:07 +00003712 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003713 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3714 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3715 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3716 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003717 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003718 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003719 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3720 I.getType(), TD) &&
3721 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3722 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003723 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003724 Op1C->getOperand(0),
3725 I.getName());
3726 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003727 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003728 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003729 }
Chris Lattnere511b742006-11-14 07:46:50 +00003730
3731 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003732 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3733 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3734 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003735 SI0->getOperand(1) == SI1->getOperand(1) &&
3736 (SI0->hasOneUse() || SI1->hasOneUse())) {
3737 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003738 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00003739 SI1->getOperand(0),
3740 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003741 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003742 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003743 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003744 }
3745
Chris Lattner99c65742007-10-24 05:38:08 +00003746 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3747 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3748 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3749 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3750 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3751 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3752 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3753 // If either of the constants are nans, then the whole thing returns
3754 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003755 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003756 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3757 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3758 RHS->getOperand(0));
3759 }
3760 }
3761 }
3762
Chris Lattner7e708292002-06-25 16:13:24 +00003763 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003764}
3765
Chris Lattnerafe91a52006-06-15 19:07:26 +00003766/// CollectBSwapParts - Look to see if the specified value defines a single byte
3767/// in the result. If it does, and if the specified byte hasn't been filled in
3768/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003769static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003770 Instruction *I = dyn_cast<Instruction>(V);
3771 if (I == 0) return true;
3772
3773 // If this is an or instruction, it is an inner node of the bswap.
3774 if (I->getOpcode() == Instruction::Or)
3775 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3776 CollectBSwapParts(I->getOperand(1), ByteValues);
3777
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003778 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003779 // If this is a shift by a constant int, and it is "24", then its operand
3780 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003781 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003782 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003783 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003784 8*(ByteValues.size()-1))
3785 return true;
3786
3787 unsigned DestNo;
3788 if (I->getOpcode() == Instruction::Shl) {
3789 // X << 24 defines the top byte with the lowest of the input bytes.
3790 DestNo = ByteValues.size()-1;
3791 } else {
3792 // X >>u 24 defines the low byte with the highest of the input bytes.
3793 DestNo = 0;
3794 }
3795
3796 // If the destination byte value is already defined, the values are or'd
3797 // together, which isn't a bswap (unless it's an or of the same bits).
3798 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3799 return true;
3800 ByteValues[DestNo] = I->getOperand(0);
3801 return false;
3802 }
3803
3804 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3805 // don't have this.
3806 Value *Shift = 0, *ShiftLHS = 0;
3807 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3808 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3809 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3810 return true;
3811 Instruction *SI = cast<Instruction>(Shift);
3812
3813 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003814 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3815 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003816 return true;
3817
3818 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3819 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003820 if (AndAmt->getValue().getActiveBits() > 64)
3821 return true;
3822 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003823 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003824 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003825 break;
3826 // Unknown mask for bswap.
3827 if (DestByte == ByteValues.size()) return true;
3828
Reid Spencerb83eb642006-10-20 07:07:24 +00003829 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003830 unsigned SrcByte;
3831 if (SI->getOpcode() == Instruction::Shl)
3832 SrcByte = DestByte - ShiftBytes;
3833 else
3834 SrcByte = DestByte + ShiftBytes;
3835
3836 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3837 if (SrcByte != ByteValues.size()-DestByte-1)
3838 return true;
3839
3840 // If the destination byte value is already defined, the values are or'd
3841 // together, which isn't a bswap (unless it's an or of the same bits).
3842 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3843 return true;
3844 ByteValues[DestByte] = SI->getOperand(0);
3845 return false;
3846}
3847
3848/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3849/// If so, insert the new bswap intrinsic and return it.
3850Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003851 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3852 if (!ITy || ITy->getBitWidth() % 16)
3853 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003854
3855 /// ByteValues - For each byte of the result, we keep track of which value
3856 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003857 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003858 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003859
3860 // Try to find all the pieces corresponding to the bswap.
3861 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3862 CollectBSwapParts(I.getOperand(1), ByteValues))
3863 return 0;
3864
3865 // Check to see if all of the bytes come from the same value.
3866 Value *V = ByteValues[0];
3867 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3868
3869 // Check to make sure that all of the bytes come from the same value.
3870 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3871 if (ByteValues[i] != V)
3872 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003873 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003874 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003875 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00003876 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003877}
3878
3879
Chris Lattner7e708292002-06-25 16:13:24 +00003880Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003881 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003882 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003883
Chris Lattner42593e62007-03-24 23:56:43 +00003884 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003885 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003886
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003887 // or X, X = X
3888 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003889 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003890
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003891 // See if we can simplify any instructions used by the instruction whose sole
3892 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003893 if (!isa<VectorType>(I.getType())) {
3894 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3895 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3896 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3897 KnownZero, KnownOne))
3898 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003899 } else if (isa<ConstantAggregateZero>(Op1)) {
3900 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3901 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3902 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3903 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003904 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003905
3906
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003907
Chris Lattner3f5b8772002-05-06 16:14:14 +00003908 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003909 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003910 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003911 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3912 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003913 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003914 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003915 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003916 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003917 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003918 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003919
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003920 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3921 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003922 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003923 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003924 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003925 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003926 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003927 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003928
3929 // Try to fold constant and into select arguments.
3930 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003931 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003932 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003933 if (isa<PHINode>(Op0))
3934 if (Instruction *NV = FoldOpIntoPhi(I))
3935 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003936 }
3937
Chris Lattner4f637d42006-01-06 17:59:59 +00003938 Value *A = 0, *B = 0;
3939 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003940
3941 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3942 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3943 return ReplaceInstUsesWith(I, Op1);
3944 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3945 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3946 return ReplaceInstUsesWith(I, Op0);
3947
Chris Lattner6423d4c2006-07-10 20:25:24 +00003948 // (A | B) | C and A | (B | C) -> bswap if possible.
3949 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003950 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003951 match(Op1, m_Or(m_Value(), m_Value())) ||
3952 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3953 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003954 if (Instruction *BSwap = MatchBSwap(I))
3955 return BSwap;
3956 }
3957
Chris Lattner6e4c6492005-05-09 04:58:36 +00003958 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3959 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003960 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003961 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00003962 InsertNewInstBefore(NOr, I);
3963 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003964 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003965 }
3966
3967 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3968 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003969 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003970 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00003971 InsertNewInstBefore(NOr, I);
3972 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003973 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003974 }
3975
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003976 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00003977 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003978 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3979 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003980 Value *V1 = 0, *V2 = 0, *V3 = 0;
3981 C1 = dyn_cast<ConstantInt>(C);
3982 C2 = dyn_cast<ConstantInt>(D);
3983 if (C1 && C2) { // (A & C1)|(B & C2)
3984 // If we have: ((V + N) & C1) | (V & C2)
3985 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3986 // replace with V+N.
3987 if (C1->getValue() == ~C2->getValue()) {
3988 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3989 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3990 // Add commutes, try both ways.
3991 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3992 return ReplaceInstUsesWith(I, A);
3993 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3994 return ReplaceInstUsesWith(I, A);
3995 }
3996 // Or commutes, try both ways.
3997 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3998 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3999 // Add commutes, try both ways.
4000 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4001 return ReplaceInstUsesWith(I, B);
4002 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4003 return ReplaceInstUsesWith(I, B);
4004 }
4005 }
Chris Lattner044e5332007-04-08 08:01:49 +00004006 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004007 }
4008
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004009 // Check to see if we have any common things being and'ed. If so, find the
4010 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004011 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4012 if (A == B) // (A & C)|(A & D) == A & (C|D)
4013 V1 = A, V2 = C, V3 = D;
4014 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4015 V1 = A, V2 = B, V3 = C;
4016 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4017 V1 = C, V2 = A, V3 = D;
4018 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4019 V1 = C, V2 = A, V3 = B;
4020
4021 if (V1) {
4022 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004023 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4024 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004025 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004026 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004027 }
Chris Lattnere511b742006-11-14 07:46:50 +00004028
4029 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004030 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4031 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4032 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004033 SI0->getOperand(1) == SI1->getOperand(1) &&
4034 (SI0->hasOneUse() || SI1->hasOneUse())) {
4035 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004036 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004037 SI1->getOperand(0),
4038 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004039 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004040 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004041 }
4042 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004043
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004044 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4045 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004046 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004047 } else {
4048 A = 0;
4049 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004050 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004051 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4052 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004053 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004054
Misha Brukmancb6267b2004-07-30 12:50:08 +00004055 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004056 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004057 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004058 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004059 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004060 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004061 }
Chris Lattnera2881962003-02-18 19:28:33 +00004062
Reid Spencere4d87aa2006-12-23 06:05:41 +00004063 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4064 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4065 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004066 return R;
4067
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004068 Value *LHSVal, *RHSVal;
4069 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004070 ICmpInst::Predicate LHSCC, RHSCC;
4071 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4072 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4073 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4074 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4075 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4076 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4077 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004078 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4079 // We can't fold (ugt x, C) | (sgt x, C2).
4080 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004081 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004082 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004083 bool NeedsSwap;
4084 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004085 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004086 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004087 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004088
4089 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004090 std::swap(LHS, RHS);
4091 std::swap(LHSCst, RHSCst);
4092 std::swap(LHSCC, RHSCC);
4093 }
4094
Reid Spencere4d87aa2006-12-23 06:05:41 +00004095 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004096 // comparing a value against two constants and or'ing the result
4097 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004098 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4099 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004100 // equal.
4101 assert(LHSCst != RHSCst && "Compares not folded above?");
4102
4103 switch (LHSCC) {
4104 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004105 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004106 switch (RHSCC) {
4107 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004108 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004109 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4110 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004111 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004112 LHSVal->getName()+".off");
4113 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004114 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004115 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004116 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004117 break; // (X == 13 | X == 15) -> no change
4118 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4119 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004120 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004121 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4122 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4123 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004124 return ReplaceInstUsesWith(I, RHS);
4125 }
4126 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004127 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004128 switch (RHSCC) {
4129 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004130 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4131 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4132 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004133 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004134 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4135 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4136 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004137 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004138 }
4139 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004140 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004141 switch (RHSCC) {
4142 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004143 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004144 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004145 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004146 // If RHSCst is [us]MAXINT, it is always false. Not handling
4147 // this can cause overflow.
4148 if (RHSCst->isMaxValue(false))
4149 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004150 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4151 false, I);
4152 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4153 break;
4154 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4155 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004156 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004157 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4158 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004159 }
4160 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004161 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004162 switch (RHSCC) {
4163 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004164 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4165 break;
4166 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004167 // If RHSCst is [us]MAXINT, it is always false. Not handling
4168 // this can cause overflow.
4169 if (RHSCst->isMaxValue(true))
4170 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004171 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4172 false, I);
4173 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4174 break;
4175 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4176 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4177 return ReplaceInstUsesWith(I, RHS);
4178 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4179 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004180 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004181 break;
4182 case ICmpInst::ICMP_UGT:
4183 switch (RHSCC) {
4184 default: assert(0 && "Unknown integer condition code!");
4185 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4186 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4187 return ReplaceInstUsesWith(I, LHS);
4188 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4189 break;
4190 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4191 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004192 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004193 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4194 break;
4195 }
4196 break;
4197 case ICmpInst::ICMP_SGT:
4198 switch (RHSCC) {
4199 default: assert(0 && "Unknown integer condition code!");
4200 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4201 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4202 return ReplaceInstUsesWith(I, LHS);
4203 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4204 break;
4205 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4206 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004207 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004208 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4209 break;
4210 }
4211 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004212 }
4213 }
4214 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004215
4216 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004217 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004218 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004219 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004220 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4221 !isa<ICmpInst>(Op1C->getOperand(0))) {
4222 const Type *SrcTy = Op0C->getOperand(0)->getType();
4223 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4224 // Only do this if the casts both really cause code to be
4225 // generated.
4226 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4227 I.getType(), TD) &&
4228 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4229 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004230 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004231 Op1C->getOperand(0),
4232 I.getName());
4233 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004234 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004235 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004236 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004237 }
Chris Lattner99c65742007-10-24 05:38:08 +00004238 }
4239
4240
4241 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4242 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4243 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4244 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004245 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4246 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004247 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4248 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4249 // If either of the constants are nans, then the whole thing returns
4250 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004251 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004252 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4253
4254 // Otherwise, no need to compare the two constants, compare the
4255 // rest.
4256 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4257 RHS->getOperand(0));
4258 }
4259 }
4260 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004261
Chris Lattner7e708292002-06-25 16:13:24 +00004262 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004263}
4264
Dan Gohman844731a2008-05-13 00:00:25 +00004265namespace {
4266
Chris Lattnerc317d392004-02-16 01:20:27 +00004267// XorSelf - Implements: X ^ X --> 0
4268struct XorSelf {
4269 Value *RHS;
4270 XorSelf(Value *rhs) : RHS(rhs) {}
4271 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4272 Instruction *apply(BinaryOperator &Xor) const {
4273 return &Xor;
4274 }
4275};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004276
Dan Gohman844731a2008-05-13 00:00:25 +00004277}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004278
Chris Lattner7e708292002-06-25 16:13:24 +00004279Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004280 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004281 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004282
Evan Chengd34af782008-03-25 20:07:13 +00004283 if (isa<UndefValue>(Op1)) {
4284 if (isa<UndefValue>(Op0))
4285 // Handle undef ^ undef -> 0 special case. This is a common
4286 // idiom (misuse).
4287 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004288 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004289 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004290
Chris Lattnerc317d392004-02-16 01:20:27 +00004291 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4292 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004293 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004294 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004295 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004296
4297 // See if we can simplify any instructions used by the instruction whose sole
4298 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004299 if (!isa<VectorType>(I.getType())) {
4300 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4301 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4302 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4303 KnownZero, KnownOne))
4304 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004305 } else if (isa<ConstantAggregateZero>(Op1)) {
4306 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004307 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004308
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004309 // Is this a ~ operation?
4310 if (Value *NotOp = dyn_castNotVal(&I)) {
4311 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4312 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4313 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4314 if (Op0I->getOpcode() == Instruction::And ||
4315 Op0I->getOpcode() == Instruction::Or) {
4316 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4317 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4318 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004319 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004320 Op0I->getOperand(1)->getName()+".not");
4321 InsertNewInstBefore(NotY, I);
4322 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004323 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004324 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004325 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004326 }
4327 }
4328 }
4329 }
4330
4331
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004332 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004333 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4334 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4335 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004336 return new ICmpInst(ICI->getInversePredicate(),
4337 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004338
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004339 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4340 return new FCmpInst(FCI->getInversePredicate(),
4341 FCI->getOperand(0), FCI->getOperand(1));
4342 }
4343
Nick Lewycky517e1f52008-05-31 19:01:33 +00004344 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4345 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4346 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4347 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4348 Instruction::CastOps Opcode = Op0C->getOpcode();
4349 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4350 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4351 Op0C->getDestTy())) {
4352 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4353 CI->getOpcode(), CI->getInversePredicate(),
4354 CI->getOperand(0), CI->getOperand(1)), I);
4355 NewCI->takeName(CI);
4356 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4357 }
4358 }
4359 }
4360 }
4361 }
4362
Reid Spencere4d87aa2006-12-23 06:05:41 +00004363 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004364 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004365 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4366 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004367 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4368 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004369 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004370 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004371 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004372
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004373 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004374 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004375 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004376 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004377 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004378 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004379 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004380 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004381 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004382 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004383 // (X + C) ^ signbit -> (X + C + signbit)
4384 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004385 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004386
Chris Lattner7c4049c2004-01-12 19:35:11 +00004387 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004388 } else if (Op0I->getOpcode() == Instruction::Or) {
4389 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004390 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004391 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4392 // Anything in both C1 and C2 is known to be zero, remove it from
4393 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004394 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004395 NewRHS = ConstantExpr::getAnd(NewRHS,
4396 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004397 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004398 I.setOperand(0, Op0I->getOperand(0));
4399 I.setOperand(1, NewRHS);
4400 return &I;
4401 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004402 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004403 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004404 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004405
4406 // Try to fold constant and into select arguments.
4407 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004408 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004409 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004410 if (isa<PHINode>(Op0))
4411 if (Instruction *NV = FoldOpIntoPhi(I))
4412 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004413 }
4414
Chris Lattner8d969642003-03-10 23:06:50 +00004415 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004416 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004417 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004418
Chris Lattner8d969642003-03-10 23:06:50 +00004419 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004420 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004421 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004422
Chris Lattner318bf792007-03-18 22:51:34 +00004423
4424 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4425 if (Op1I) {
4426 Value *A, *B;
4427 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4428 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004429 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004430 I.swapOperands();
4431 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004432 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004433 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004434 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004435 }
Chris Lattner318bf792007-03-18 22:51:34 +00004436 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4437 if (Op0 == A) // A^(A^B) == B
4438 return ReplaceInstUsesWith(I, B);
4439 else if (Op0 == B) // A^(B^A) == B
4440 return ReplaceInstUsesWith(I, A);
4441 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004442 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004443 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004444 std::swap(A, B);
4445 }
Chris Lattner318bf792007-03-18 22:51:34 +00004446 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004447 I.swapOperands(); // Simplified below.
4448 std::swap(Op0, Op1);
4449 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004450 }
Chris Lattner318bf792007-03-18 22:51:34 +00004451 }
4452
4453 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4454 if (Op0I) {
4455 Value *A, *B;
4456 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4457 if (A == Op1) // (B|A)^B == (A|B)^B
4458 std::swap(A, B);
4459 if (B == Op1) { // (A|B)^B == A & ~B
4460 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004461 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4462 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004463 }
Chris Lattner318bf792007-03-18 22:51:34 +00004464 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4465 if (Op1 == A) // (A^B)^A == B
4466 return ReplaceInstUsesWith(I, B);
4467 else if (Op1 == B) // (B^A)^A == B
4468 return ReplaceInstUsesWith(I, A);
4469 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4470 if (A == Op1) // (A&B)^A -> (B&A)^A
4471 std::swap(A, B);
4472 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004473 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004474 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004475 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4476 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004477 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004478 }
Chris Lattner318bf792007-03-18 22:51:34 +00004479 }
4480
4481 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4482 if (Op0I && Op1I && Op0I->isShift() &&
4483 Op0I->getOpcode() == Op1I->getOpcode() &&
4484 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4485 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4486 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004487 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004488 Op1I->getOperand(0),
4489 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004490 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004491 Op1I->getOperand(1));
4492 }
4493
4494 if (Op0I && Op1I) {
4495 Value *A, *B, *C, *D;
4496 // (A & B)^(A | B) -> A ^ B
4497 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4498 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4499 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004500 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004501 }
4502 // (A | B)^(A & B) -> A ^ B
4503 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4504 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4505 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004506 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004507 }
4508
4509 // (A & B)^(C & D)
4510 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4511 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4512 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4513 // (X & Y)^(X & Y) -> (Y^Z) & X
4514 Value *X = 0, *Y = 0, *Z = 0;
4515 if (A == C)
4516 X = A, Y = B, Z = D;
4517 else if (A == D)
4518 X = A, Y = B, Z = C;
4519 else if (B == C)
4520 X = B, Y = A, Z = D;
4521 else if (B == D)
4522 X = B, Y = A, Z = C;
4523
4524 if (X) {
4525 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004526 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4527 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004528 }
4529 }
4530 }
4531
Reid Spencere4d87aa2006-12-23 06:05:41 +00004532 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4533 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4534 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004535 return R;
4536
Chris Lattner6fc205f2006-05-05 06:39:07 +00004537 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004538 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004539 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004540 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4541 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004542 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004543 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004544 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4545 I.getType(), TD) &&
4546 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4547 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004548 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004549 Op1C->getOperand(0),
4550 I.getName());
4551 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004552 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004553 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004554 }
Chris Lattner99c65742007-10-24 05:38:08 +00004555 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00004556
Chris Lattner7e708292002-06-25 16:13:24 +00004557 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004558}
4559
Chris Lattnera96879a2004-09-29 17:40:11 +00004560/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4561/// overflowed for this type.
4562static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004563 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004564 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004565
Reid Spencere4e40032007-03-21 23:19:50 +00004566 if (IsSigned)
4567 if (In2->getValue().isNegative())
4568 return Result->getValue().sgt(In1->getValue());
4569 else
4570 return Result->getValue().slt(In1->getValue());
4571 else
4572 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004573}
4574
Chris Lattner574da9b2005-01-13 20:14:25 +00004575/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4576/// code necessary to compute the offset from the base pointer (without adding
4577/// in the base pointer). Return the result as a signed integer of intptr size.
4578static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4579 TargetData &TD = IC.getTargetData();
4580 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004581 const Type *IntPtrTy = TD.getIntPtrType();
4582 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004583
4584 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004585 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004586 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004587
Chris Lattner574da9b2005-01-13 20:14:25 +00004588 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4589 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004590 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004591 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4592 if (OpC->isZero()) continue;
4593
4594 // Handle a struct index, which adds its field offset to the pointer.
4595 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4596 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4597
4598 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4599 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004600 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004601 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004602 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004603 ConstantInt::get(IntPtrTy, Size),
4604 GEP->getName()+".offs"), I);
4605 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004606 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004607
4608 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4609 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4610 Scale = ConstantExpr::getMul(OC, Scale);
4611 if (Constant *RC = dyn_cast<Constant>(Result))
4612 Result = ConstantExpr::getAdd(RC, Scale);
4613 else {
4614 // Emit an add instruction.
4615 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004616 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004617 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004618 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004619 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004620 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004621 // Convert to correct type.
4622 if (Op->getType() != IntPtrTy) {
4623 if (Constant *OpC = dyn_cast<Constant>(Op))
4624 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4625 else
4626 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4627 Op->getName()+".c"), I);
4628 }
4629 if (Size != 1) {
4630 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4631 if (Constant *OpC = dyn_cast<Constant>(Op))
4632 Op = ConstantExpr::getMul(OpC, Scale);
4633 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004634 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004635 GEP->getName()+".idx"), I);
4636 }
4637
4638 // Emit an add instruction.
4639 if (isa<Constant>(Op) && isa<Constant>(Result))
4640 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4641 cast<Constant>(Result));
4642 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004643 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004644 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004645 }
4646 return Result;
4647}
4648
Chris Lattner10c0d912008-04-22 02:53:33 +00004649
4650/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4651/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4652/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4653/// complex, and scales are involved. The above expression would also be legal
4654/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4655/// later form is less amenable to optimization though, and we are allowed to
4656/// generate the first by knowing that pointer arithmetic doesn't overflow.
4657///
4658/// If we can't emit an optimized form for this expression, this returns null.
4659///
4660static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4661 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00004662 TargetData &TD = IC.getTargetData();
4663 gep_type_iterator GTI = gep_type_begin(GEP);
4664
4665 // Check to see if this gep only has a single variable index. If so, and if
4666 // any constant indices are a multiple of its scale, then we can compute this
4667 // in terms of the scale of the variable index. For example, if the GEP
4668 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4669 // because the expression will cross zero at the same point.
4670 unsigned i, e = GEP->getNumOperands();
4671 int64_t Offset = 0;
4672 for (i = 1; i != e; ++i, ++GTI) {
4673 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4674 // Compute the aggregate offset of constant indices.
4675 if (CI->isZero()) continue;
4676
4677 // Handle a struct index, which adds its field offset to the pointer.
4678 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4679 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4680 } else {
4681 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4682 Offset += Size*CI->getSExtValue();
4683 }
4684 } else {
4685 // Found our variable index.
4686 break;
4687 }
4688 }
4689
4690 // If there are no variable indices, we must have a constant offset, just
4691 // evaluate it the general way.
4692 if (i == e) return 0;
4693
4694 Value *VariableIdx = GEP->getOperand(i);
4695 // Determine the scale factor of the variable element. For example, this is
4696 // 4 if the variable index is into an array of i32.
4697 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4698
4699 // Verify that there are no other variable indices. If so, emit the hard way.
4700 for (++i, ++GTI; i != e; ++i, ++GTI) {
4701 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4702 if (!CI) return 0;
4703
4704 // Compute the aggregate offset of constant indices.
4705 if (CI->isZero()) continue;
4706
4707 // Handle a struct index, which adds its field offset to the pointer.
4708 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4709 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4710 } else {
4711 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4712 Offset += Size*CI->getSExtValue();
4713 }
4714 }
4715
4716 // Okay, we know we have a single variable index, which must be a
4717 // pointer/array/vector index. If there is no offset, life is simple, return
4718 // the index.
4719 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4720 if (Offset == 0) {
4721 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4722 // we don't need to bother extending: the extension won't affect where the
4723 // computation crosses zero.
4724 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4725 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4726 VariableIdx->getNameStart(), &I);
4727 return VariableIdx;
4728 }
4729
4730 // Otherwise, there is an index. The computation we will do will be modulo
4731 // the pointer size, so get it.
4732 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4733
4734 Offset &= PtrSizeMask;
4735 VariableScale &= PtrSizeMask;
4736
4737 // To do this transformation, any constant index must be a multiple of the
4738 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4739 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4740 // multiple of the variable scale.
4741 int64_t NewOffs = Offset / (int64_t)VariableScale;
4742 if (Offset != NewOffs*(int64_t)VariableScale)
4743 return 0;
4744
4745 // Okay, we can do this evaluation. Start by converting the index to intptr.
4746 const Type *IntPtrTy = TD.getIntPtrType();
4747 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004748 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00004749 true /*SExt*/,
4750 VariableIdx->getNameStart(), &I);
4751 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004752 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00004753}
4754
4755
Reid Spencere4d87aa2006-12-23 06:05:41 +00004756/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004757/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004758Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4759 ICmpInst::Predicate Cond,
4760 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004761 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004762
Chris Lattner10c0d912008-04-22 02:53:33 +00004763 // Look through bitcasts.
4764 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4765 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004766
Chris Lattner574da9b2005-01-13 20:14:25 +00004767 Value *PtrBase = GEPLHS->getOperand(0);
4768 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004769 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00004770 // This transformation (ignoring the base and scales) is valid because we
4771 // know pointers can't overflow. See if we can output an optimized form.
4772 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4773
4774 // If not, synthesize the offset the hard way.
4775 if (Offset == 0)
4776 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00004777 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4778 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004779 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004780 // If the base pointers are different, but the indices are the same, just
4781 // compare the base pointer.
4782 if (PtrBase != GEPRHS->getOperand(0)) {
4783 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004784 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004785 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004786 if (IndicesTheSame)
4787 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4788 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4789 IndicesTheSame = false;
4790 break;
4791 }
4792
4793 // If all indices are the same, just compare the base pointers.
4794 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004795 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4796 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004797
4798 // Otherwise, the base pointers are different and the indices are
4799 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004800 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004801 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004802
Chris Lattnere9d782b2005-01-13 22:25:21 +00004803 // If one of the GEPs has all zero indices, recurse.
4804 bool AllZeros = true;
4805 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4806 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4807 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4808 AllZeros = false;
4809 break;
4810 }
4811 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004812 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4813 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004814
4815 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004816 AllZeros = true;
4817 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4818 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4819 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4820 AllZeros = false;
4821 break;
4822 }
4823 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004824 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004825
Chris Lattner4401c9c2005-01-14 00:20:05 +00004826 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4827 // If the GEPs only differ by one index, compare it.
4828 unsigned NumDifferences = 0; // Keep track of # differences.
4829 unsigned DiffOperand = 0; // The operand that differs.
4830 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4831 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004832 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4833 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004834 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004835 NumDifferences = 2;
4836 break;
4837 } else {
4838 if (NumDifferences++) break;
4839 DiffOperand = i;
4840 }
4841 }
4842
4843 if (NumDifferences == 0) // SAME GEP?
4844 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004845 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00004846 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00004847
Chris Lattner4401c9c2005-01-14 00:20:05 +00004848 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004849 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4850 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004851 // Make sure we do a signed comparison here.
4852 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004853 }
4854 }
4855
Reid Spencere4d87aa2006-12-23 06:05:41 +00004856 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004857 // the result to fold to a constant!
4858 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4859 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4860 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4861 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4862 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004863 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004864 }
4865 }
4866 return 0;
4867}
4868
Chris Lattnera5406232008-05-19 20:18:56 +00004869/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4870///
4871Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4872 Instruction *LHSI,
4873 Constant *RHSC) {
4874 if (!isa<ConstantFP>(RHSC)) return 0;
4875 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4876
4877 // Get the width of the mantissa. We don't want to hack on conversions that
4878 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00004879 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00004880 if (MantissaWidth == -1) return 0; // Unknown.
4881
4882 // Check to see that the input is converted from an integer type that is small
4883 // enough that preserves all bits. TODO: check here for "known" sign bits.
4884 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4885 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4886
4887 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4888 if (isa<UIToFPInst>(LHSI))
4889 ++InputSize;
4890
4891 // If the conversion would lose info, don't hack on this.
4892 if ((int)InputSize > MantissaWidth)
4893 return 0;
4894
4895 // Otherwise, we can potentially simplify the comparison. We know that it
4896 // will always come through as an integer value and we know the constant is
4897 // not a NAN (it would have been previously simplified).
4898 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4899
4900 ICmpInst::Predicate Pred;
4901 switch (I.getPredicate()) {
4902 default: assert(0 && "Unexpected predicate!");
4903 case FCmpInst::FCMP_UEQ:
4904 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4905 case FCmpInst::FCMP_UGT:
4906 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4907 case FCmpInst::FCMP_UGE:
4908 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4909 case FCmpInst::FCMP_ULT:
4910 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4911 case FCmpInst::FCMP_ULE:
4912 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4913 case FCmpInst::FCMP_UNE:
4914 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4915 case FCmpInst::FCMP_ORD:
4916 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4917 case FCmpInst::FCMP_UNO:
4918 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4919 }
4920
4921 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4922
4923 // Now we know that the APFloat is a normal number, zero or inf.
4924
Chris Lattner85162782008-05-20 03:50:52 +00004925 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00004926 // comparing an i8 to 300.0.
4927 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4928
4929 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4930 // and large values.
4931 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4932 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4933 APFloat::rmNearestTiesToEven);
4934 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004935 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4936 Pred == ICmpInst::ICMP_SLE)
Chris Lattnera5406232008-05-19 20:18:56 +00004937 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4938 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4939 }
4940
4941 // See if the RHS value is < SignedMin.
4942 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4943 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4944 APFloat::rmNearestTiesToEven);
4945 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004946 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4947 Pred == ICmpInst::ICMP_SGE)
Chris Lattnera5406232008-05-19 20:18:56 +00004948 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4949 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4950 }
4951
4952 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4953 // it may still be fractional. See if it is fractional by casting the FP
4954 // value to the integer value and back, checking for equality. Don't do this
4955 // for zero, because -0.0 is not fractional.
4956 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4957 if (!RHS.isZero() &&
4958 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4959 // If we had a comparison against a fractional value, we have to adjust
4960 // the compare predicate and sometimes the value. RHSC is rounded towards
4961 // zero at this point.
4962 switch (Pred) {
4963 default: assert(0 && "Unexpected integer comparison!");
4964 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
4965 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4966 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
4967 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4968 case ICmpInst::ICMP_SLE:
4969 // (float)int <= 4.4 --> int <= 4
4970 // (float)int <= -4.4 --> int < -4
4971 if (RHS.isNegative())
4972 Pred = ICmpInst::ICMP_SLT;
4973 break;
4974 case ICmpInst::ICMP_SLT:
4975 // (float)int < -4.4 --> int < -4
4976 // (float)int < 4.4 --> int <= 4
4977 if (!RHS.isNegative())
4978 Pred = ICmpInst::ICMP_SLE;
4979 break;
4980 case ICmpInst::ICMP_SGT:
4981 // (float)int > 4.4 --> int > 4
4982 // (float)int > -4.4 --> int >= -4
4983 if (RHS.isNegative())
4984 Pred = ICmpInst::ICMP_SGE;
4985 break;
4986 case ICmpInst::ICMP_SGE:
4987 // (float)int >= -4.4 --> int >= -4
4988 // (float)int >= 4.4 --> int > 4
4989 if (!RHS.isNegative())
4990 Pred = ICmpInst::ICMP_SGT;
4991 break;
4992 }
4993 }
4994
4995 // Lower this FP comparison into an appropriate integer version of the
4996 // comparison.
4997 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4998}
4999
Reid Spencere4d87aa2006-12-23 06:05:41 +00005000Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5001 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005002 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005003
Chris Lattner58e97462007-01-14 19:42:17 +00005004 // Fold trivial predicates.
5005 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5006 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5007 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5008 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5009
5010 // Simplify 'fcmp pred X, X'
5011 if (Op0 == Op1) {
5012 switch (I.getPredicate()) {
5013 default: assert(0 && "Unknown predicate!");
5014 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5015 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5016 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5017 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5018 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5019 case FCmpInst::FCMP_OLT: // True if ordered and less than
5020 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5021 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5022
5023 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5024 case FCmpInst::FCMP_ULT: // True if unordered or less than
5025 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5026 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5027 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5028 I.setPredicate(FCmpInst::FCMP_UNO);
5029 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5030 return &I;
5031
5032 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5033 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5034 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5035 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5036 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5037 I.setPredicate(FCmpInst::FCMP_ORD);
5038 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5039 return &I;
5040 }
5041 }
5042
Reid Spencere4d87aa2006-12-23 06:05:41 +00005043 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005044 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005045
Reid Spencere4d87aa2006-12-23 06:05:41 +00005046 // Handle fcmp with constant RHS
5047 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005048 // If the constant is a nan, see if we can fold the comparison based on it.
5049 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5050 if (CFP->getValueAPF().isNaN()) {
5051 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5052 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005053 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5054 "Comparison must be either ordered or unordered!");
5055 // True if unordered.
5056 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005057 }
5058 }
5059
Reid Spencere4d87aa2006-12-23 06:05:41 +00005060 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5061 switch (LHSI->getOpcode()) {
5062 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005063 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5064 // block. If in the same block, we're encouraging jump threading. If
5065 // not, we are just pessimizing the code by making an i1 phi.
5066 if (LHSI->getParent() == I.getParent())
5067 if (Instruction *NV = FoldOpIntoPhi(I))
5068 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005069 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005070 case Instruction::SIToFP:
5071 case Instruction::UIToFP:
5072 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5073 return NV;
5074 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005075 case Instruction::Select:
5076 // If either operand of the select is a constant, we can fold the
5077 // comparison into the select arms, which will cause one to be
5078 // constant folded and the select turned into a bitwise or.
5079 Value *Op1 = 0, *Op2 = 0;
5080 if (LHSI->hasOneUse()) {
5081 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5082 // Fold the known value into the constant operand.
5083 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5084 // Insert a new FCmp of the other select operand.
5085 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5086 LHSI->getOperand(2), RHSC,
5087 I.getName()), I);
5088 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5089 // Fold the known value into the constant operand.
5090 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5091 // Insert a new FCmp of the other select operand.
5092 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5093 LHSI->getOperand(1), RHSC,
5094 I.getName()), I);
5095 }
5096 }
5097
5098 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005099 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005100 break;
5101 }
5102 }
5103
5104 return Changed ? &I : 0;
5105}
5106
5107Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5108 bool Changed = SimplifyCompare(I);
5109 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5110 const Type *Ty = Op0->getType();
5111
5112 // icmp X, X
5113 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005114 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005115 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005116
5117 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005118 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005119
Reid Spencere4d87aa2006-12-23 06:05:41 +00005120 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005121 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005122 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5123 isa<ConstantPointerNull>(Op0)) &&
5124 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005125 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005126 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005127 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005128
Reid Spencere4d87aa2006-12-23 06:05:41 +00005129 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005130 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005131 switch (I.getPredicate()) {
5132 default: assert(0 && "Invalid icmp instruction!");
5133 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005134 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005135 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005136 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005137 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005138 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005139 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005140
Reid Spencere4d87aa2006-12-23 06:05:41 +00005141 case ICmpInst::ICMP_UGT:
5142 case ICmpInst::ICMP_SGT:
5143 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005144 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005145 case ICmpInst::ICMP_ULT:
5146 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005147 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005148 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005149 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005150 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005151 case ICmpInst::ICMP_UGE:
5152 case ICmpInst::ICMP_SGE:
5153 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005154 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005155 case ICmpInst::ICMP_ULE:
5156 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005157 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005158 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005159 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005160 }
5161 }
Chris Lattner8b170942002-08-09 23:47:40 +00005162 }
5163
Chris Lattner2be51ae2004-06-09 04:24:29 +00005164 // See if we are doing a comparison between a constant and an instruction that
5165 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005166 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005167 Value *A, *B;
5168
Chris Lattnerb6566012008-01-05 01:18:20 +00005169 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5170 if (I.isEquality() && CI->isNullValue() &&
5171 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5172 // (icmp cond A B) if cond is equality
5173 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005174 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005175
Reid Spencere4d87aa2006-12-23 06:05:41 +00005176 switch (I.getPredicate()) {
5177 default: break;
5178 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5179 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005180 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005181 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5182 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5183 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5184 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005185 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5186 if (CI->isMinValue(true))
5187 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5188 ConstantInt::getAllOnesValue(Op0->getType()));
5189
Reid Spencere4d87aa2006-12-23 06:05:41 +00005190 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005191
Reid Spencere4d87aa2006-12-23 06:05:41 +00005192 case ICmpInst::ICMP_SLT:
5193 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005194 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005195 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5196 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5197 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5198 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5199 break;
5200
5201 case ICmpInst::ICMP_UGT:
5202 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005203 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005204 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5205 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5206 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5207 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005208
5209 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5210 if (CI->isMaxValue(true))
5211 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5212 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005213 break;
5214
5215 case ICmpInst::ICMP_SGT:
5216 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005217 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005218 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5219 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5220 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5221 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5222 break;
5223
5224 case ICmpInst::ICMP_ULE:
5225 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005226 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005227 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5228 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5229 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5230 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5231 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005232
Reid Spencere4d87aa2006-12-23 06:05:41 +00005233 case ICmpInst::ICMP_SLE:
5234 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005235 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005236 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5237 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5238 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5239 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5240 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005241
Reid Spencere4d87aa2006-12-23 06:05:41 +00005242 case ICmpInst::ICMP_UGE:
5243 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005244 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005245 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5246 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5247 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5248 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5249 break;
5250
5251 case ICmpInst::ICMP_SGE:
5252 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005253 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005254 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5255 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5256 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5257 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5258 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005259 }
5260
Reid Spencere4d87aa2006-12-23 06:05:41 +00005261 // If we still have a icmp le or icmp ge instruction, turn it into the
5262 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005263 // already been handled above, this requires little checking.
5264 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005265 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005266 default: break;
5267 case ICmpInst::ICMP_ULE:
5268 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5269 case ICmpInst::ICMP_SLE:
5270 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5271 case ICmpInst::ICMP_UGE:
5272 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5273 case ICmpInst::ICMP_SGE:
5274 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005275 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005276
5277 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005278 // in the input. If this comparison is a normal comparison, it demands all
5279 // bits, if it is a sign bit comparison, it only demands the sign bit.
5280
5281 bool UnusedBit;
5282 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5283
Reid Spencer0460fb32007-03-22 20:36:03 +00005284 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5285 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005286 if (SimplifyDemandedBits(Op0,
5287 isSignBit ? APInt::getSignBit(BitWidth)
5288 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005289 KnownZero, KnownOne, 0))
5290 return &I;
5291
5292 // Given the known and unknown bits, compute a range that the LHS could be
5293 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005294 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005295 // Compute the Min, Max and RHS values based on the known bits. For the
5296 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005297 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5298 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005299 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005300 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5301 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005302 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005303 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5304 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005305 }
5306 switch (I.getPredicate()) { // LE/GE have been folded already.
5307 default: assert(0 && "Unknown icmp opcode!");
5308 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005309 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005310 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005311 break;
5312 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005313 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005314 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005315 break;
5316 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005317 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005318 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005319 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005320 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005321 break;
5322 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005323 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005324 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005325 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005326 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005327 break;
5328 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005329 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005330 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005331 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005332 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005333 break;
5334 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005335 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005336 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005337 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005338 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005339 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005340 }
5341 }
5342
Reid Spencere4d87aa2006-12-23 06:05:41 +00005343 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005344 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005345 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005346 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005347 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5348 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005349 }
5350
Chris Lattner01deb9d2007-04-03 17:43:25 +00005351 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005352 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5353 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5354 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005355 case Instruction::GetElementPtr:
5356 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005357 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005358 bool isAllZeros = true;
5359 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5360 if (!isa<Constant>(LHSI->getOperand(i)) ||
5361 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5362 isAllZeros = false;
5363 break;
5364 }
5365 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005366 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005367 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5368 }
5369 break;
5370
Chris Lattner6970b662005-04-23 15:31:55 +00005371 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005372 // Only fold icmp into the PHI if the phi and fcmp are in the same
5373 // block. If in the same block, we're encouraging jump threading. If
5374 // not, we are just pessimizing the code by making an i1 phi.
5375 if (LHSI->getParent() == I.getParent())
5376 if (Instruction *NV = FoldOpIntoPhi(I))
5377 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005378 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005379 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005380 // If either operand of the select is a constant, we can fold the
5381 // comparison into the select arms, which will cause one to be
5382 // constant folded and the select turned into a bitwise or.
5383 Value *Op1 = 0, *Op2 = 0;
5384 if (LHSI->hasOneUse()) {
5385 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5386 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005387 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5388 // Insert a new ICmp of the other select operand.
5389 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5390 LHSI->getOperand(2), RHSC,
5391 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005392 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5393 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005394 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5395 // Insert a new ICmp of the other select operand.
5396 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5397 LHSI->getOperand(1), RHSC,
5398 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005399 }
5400 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005401
Chris Lattner6970b662005-04-23 15:31:55 +00005402 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005403 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005404 break;
5405 }
Chris Lattner4802d902007-04-06 18:57:34 +00005406 case Instruction::Malloc:
5407 // If we have (malloc != null), and if the malloc has a single use, we
5408 // can assume it is successful and remove the malloc.
5409 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5410 AddToWorkList(LHSI);
5411 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005412 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005413 }
5414 break;
5415 }
Chris Lattner6970b662005-04-23 15:31:55 +00005416 }
5417
Reid Spencere4d87aa2006-12-23 06:05:41 +00005418 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005419 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005420 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005421 return NI;
5422 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005423 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5424 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005425 return NI;
5426
Reid Spencere4d87aa2006-12-23 06:05:41 +00005427 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005428 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5429 // now.
5430 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5431 if (isa<PointerType>(Op0->getType()) &&
5432 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005433 // We keep moving the cast from the left operand over to the right
5434 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005435 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005436
Chris Lattner57d86372007-01-06 01:45:59 +00005437 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5438 // so eliminate it as well.
5439 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5440 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005441
Chris Lattnerde90b762003-11-03 04:25:02 +00005442 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005443 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005444 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005445 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005446 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005447 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005448 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005449 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005450 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005451 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005452 }
Chris Lattner57d86372007-01-06 01:45:59 +00005453 }
5454
5455 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005456 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005457 // This comes up when you have code like
5458 // int X = A < B;
5459 // if (X) ...
5460 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005461 // with a constant or another cast from the same type.
5462 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005463 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005464 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005465 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005466
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005467 // ~x < ~y --> y < x
5468 { Value *A, *B;
5469 if (match(Op0, m_Not(m_Value(A))) &&
5470 match(Op1, m_Not(m_Value(B))))
5471 return new ICmpInst(I.getPredicate(), B, A);
5472 }
5473
Chris Lattner65b72ba2006-09-18 04:22:48 +00005474 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005475 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005476
5477 // -x == -y --> x == y
5478 if (match(Op0, m_Neg(m_Value(A))) &&
5479 match(Op1, m_Neg(m_Value(B))))
5480 return new ICmpInst(I.getPredicate(), A, B);
5481
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005482 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5483 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5484 Value *OtherVal = A == Op1 ? B : A;
5485 return new ICmpInst(I.getPredicate(), OtherVal,
5486 Constant::getNullValue(A->getType()));
5487 }
5488
5489 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5490 // A^c1 == C^c2 --> A == C^(c1^c2)
5491 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5492 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5493 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005494 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005495 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005496 return new ICmpInst(I.getPredicate(), A,
5497 InsertNewInstBefore(Xor, I));
5498 }
5499
5500 // A^B == A^D -> B == D
5501 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5502 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5503 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5504 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5505 }
5506 }
5507
5508 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5509 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005510 // A == (A^B) -> B == 0
5511 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005512 return new ICmpInst(I.getPredicate(), OtherVal,
5513 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005514 }
5515 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005516 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005517 return new ICmpInst(I.getPredicate(), B,
5518 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005519 }
5520 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005521 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005522 return new ICmpInst(I.getPredicate(), B,
5523 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005524 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005525
Chris Lattner9c2328e2006-11-14 06:06:06 +00005526 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5527 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5528 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5529 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5530 Value *X = 0, *Y = 0, *Z = 0;
5531
5532 if (A == C) {
5533 X = B; Y = D; Z = A;
5534 } else if (A == D) {
5535 X = B; Y = C; Z = A;
5536 } else if (B == C) {
5537 X = A; Y = D; Z = B;
5538 } else if (B == D) {
5539 X = A; Y = C; Z = B;
5540 }
5541
5542 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005543 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5544 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005545 I.setOperand(0, Op1);
5546 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5547 return &I;
5548 }
5549 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005550 }
Chris Lattner7e708292002-06-25 16:13:24 +00005551 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005552}
5553
Chris Lattner562ef782007-06-20 23:46:26 +00005554
5555/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5556/// and CmpRHS are both known to be integer constants.
5557Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5558 ConstantInt *DivRHS) {
5559 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5560 const APInt &CmpRHSV = CmpRHS->getValue();
5561
5562 // FIXME: If the operand types don't match the type of the divide
5563 // then don't attempt this transform. The code below doesn't have the
5564 // logic to deal with a signed divide and an unsigned compare (and
5565 // vice versa). This is because (x /s C1) <s C2 produces different
5566 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5567 // (x /u C1) <u C2. Simply casting the operands and result won't
5568 // work. :( The if statement below tests that condition and bails
5569 // if it finds it.
5570 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5571 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5572 return 0;
5573 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005574 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005575
5576 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5577 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5578 // C2 (CI). By solving for X we can turn this into a range check
5579 // instead of computing a divide.
5580 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5581
5582 // Determine if the product overflows by seeing if the product is
5583 // not equal to the divide. Make sure we do the same kind of divide
5584 // as in the LHS instruction that we're folding.
5585 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5586 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5587
5588 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005589 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005590
Chris Lattner1dbfd482007-06-21 18:11:19 +00005591 // Figure out the interval that is being checked. For example, a comparison
5592 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5593 // Compute this interval based on the constants involved and the signedness of
5594 // the compare/divide. This computes a half-open interval, keeping track of
5595 // whether either value in the interval overflows. After analysis each
5596 // overflow variable is set to 0 if it's corresponding bound variable is valid
5597 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5598 int LoOverflow = 0, HiOverflow = 0;
5599 ConstantInt *LoBound = 0, *HiBound = 0;
5600
5601
Chris Lattner562ef782007-06-20 23:46:26 +00005602 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005603 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005604 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005605 HiOverflow = LoOverflow = ProdOV;
5606 if (!HiOverflow)
5607 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005608 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005609 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005610 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005611 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5612 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005613 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005614 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5615 HiOverflow = LoOverflow = ProdOV;
5616 if (!HiOverflow)
5617 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005618 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005619 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005620 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5621 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005622 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005623 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005624 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005625 }
Dan Gohman76491272008-02-13 22:09:18 +00005626 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005627 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005628 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005629 LoBound = AddOne(DivRHS);
5630 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005631 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5632 HiOverflow = 1; // [INTMIN+1, overflow)
5633 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5634 }
Dan Gohman76491272008-02-13 22:09:18 +00005635 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005636 // e.g. X/-5 op 3 --> [-19, -14)
5637 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005638 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005639 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005640 HiBound = AddOne(Prod);
5641 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005642 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005643 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005644 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005645 HiBound = Subtract(Prod, DivRHS);
5646 }
5647
Chris Lattner1dbfd482007-06-21 18:11:19 +00005648 // Dividing by a negative swaps the condition. LT <-> GT
5649 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005650 }
5651
5652 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005653 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005654 default: assert(0 && "Unhandled icmp opcode!");
5655 case ICmpInst::ICMP_EQ:
5656 if (LoOverflow && HiOverflow)
5657 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5658 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005659 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005660 ICmpInst::ICMP_UGE, X, LoBound);
5661 else if (LoOverflow)
5662 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5663 ICmpInst::ICMP_ULT, X, HiBound);
5664 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005665 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005666 case ICmpInst::ICMP_NE:
5667 if (LoOverflow && HiOverflow)
5668 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5669 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005670 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005671 ICmpInst::ICMP_ULT, X, LoBound);
5672 else if (LoOverflow)
5673 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5674 ICmpInst::ICMP_UGE, X, HiBound);
5675 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005676 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005677 case ICmpInst::ICMP_ULT:
5678 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005679 if (LoOverflow == +1) // Low bound is greater than input range.
5680 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5681 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005682 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005683 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005684 case ICmpInst::ICMP_UGT:
5685 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005686 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005687 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005688 else if (HiOverflow == -1) // High bound less than input range.
5689 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5690 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005691 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5692 else
5693 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5694 }
5695}
5696
5697
Chris Lattner01deb9d2007-04-03 17:43:25 +00005698/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5699///
5700Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5701 Instruction *LHSI,
5702 ConstantInt *RHS) {
5703 const APInt &RHSV = RHS->getValue();
5704
5705 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005706 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005707 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5708 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5709 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005710 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5711 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005712 Value *CompareVal = LHSI->getOperand(0);
5713
5714 // If the sign bit of the XorCST is not set, there is no change to
5715 // the operation, just stop using the Xor.
5716 if (!XorCST->getValue().isNegative()) {
5717 ICI.setOperand(0, CompareVal);
5718 AddToWorkList(LHSI);
5719 return &ICI;
5720 }
5721
5722 // Was the old condition true if the operand is positive?
5723 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5724
5725 // If so, the new one isn't.
5726 isTrueIfPositive ^= true;
5727
5728 if (isTrueIfPositive)
5729 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5730 else
5731 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5732 }
5733 }
5734 break;
5735 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5736 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5737 LHSI->getOperand(0)->hasOneUse()) {
5738 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5739
5740 // If the LHS is an AND of a truncating cast, we can widen the
5741 // and/compare to be the input width without changing the value
5742 // produced, eliminating a cast.
5743 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5744 // We can do this transformation if either the AND constant does not
5745 // have its sign bit set or if it is an equality comparison.
5746 // Extending a relational comparison when we're checking the sign
5747 // bit would not work.
5748 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005749 (ICI.isEquality() ||
5750 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005751 uint32_t BitWidth =
5752 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5753 APInt NewCST = AndCST->getValue();
5754 NewCST.zext(BitWidth);
5755 APInt NewCI = RHSV;
5756 NewCI.zext(BitWidth);
5757 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005758 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00005759 ConstantInt::get(NewCST),LHSI->getName());
5760 InsertNewInstBefore(NewAnd, ICI);
5761 return new ICmpInst(ICI.getPredicate(), NewAnd,
5762 ConstantInt::get(NewCI));
5763 }
5764 }
5765
5766 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5767 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5768 // happens a LOT in code produced by the C front-end, for bitfield
5769 // access.
5770 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5771 if (Shift && !Shift->isShift())
5772 Shift = 0;
5773
5774 ConstantInt *ShAmt;
5775 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5776 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5777 const Type *AndTy = AndCST->getType(); // Type of the and.
5778
5779 // We can fold this as long as we can't shift unknown bits
5780 // into the mask. This can only happen with signed shift
5781 // rights, as they sign-extend.
5782 if (ShAmt) {
5783 bool CanFold = Shift->isLogicalShift();
5784 if (!CanFold) {
5785 // To test for the bad case of the signed shr, see if any
5786 // of the bits shifted in could be tested after the mask.
5787 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5788 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5789
5790 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5791 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5792 AndCST->getValue()) == 0)
5793 CanFold = true;
5794 }
5795
5796 if (CanFold) {
5797 Constant *NewCst;
5798 if (Shift->getOpcode() == Instruction::Shl)
5799 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5800 else
5801 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5802
5803 // Check to see if we are shifting out any of the bits being
5804 // compared.
5805 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5806 // If we shifted bits out, the fold is not going to work out.
5807 // As a special case, check to see if this means that the
5808 // result is always true or false now.
5809 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5810 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5811 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5812 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5813 } else {
5814 ICI.setOperand(1, NewCst);
5815 Constant *NewAndCST;
5816 if (Shift->getOpcode() == Instruction::Shl)
5817 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5818 else
5819 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5820 LHSI->setOperand(1, NewAndCST);
5821 LHSI->setOperand(0, Shift->getOperand(0));
5822 AddToWorkList(Shift); // Shift is dead.
5823 AddUsesToWorkList(ICI);
5824 return &ICI;
5825 }
5826 }
5827 }
5828
5829 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5830 // preferable because it allows the C<<Y expression to be hoisted out
5831 // of a loop if Y is invariant and X is not.
5832 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5833 ICI.isEquality() && !Shift->isArithmeticShift() &&
5834 isa<Instruction>(Shift->getOperand(0))) {
5835 // Compute C << Y.
5836 Value *NS;
5837 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005838 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005839 Shift->getOperand(1), "tmp");
5840 } else {
5841 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005842 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005843 Shift->getOperand(1), "tmp");
5844 }
5845 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5846
5847 // Compute X & (C << Y).
5848 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005849 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00005850 InsertNewInstBefore(NewAnd, ICI);
5851
5852 ICI.setOperand(0, NewAnd);
5853 return &ICI;
5854 }
5855 }
5856 break;
5857
Chris Lattnera0141b92007-07-15 20:42:37 +00005858 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5859 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5860 if (!ShAmt) break;
5861
5862 uint32_t TypeBits = RHSV.getBitWidth();
5863
5864 // Check that the shift amount is in range. If not, don't perform
5865 // undefined shifts. When the shift is visited it will be
5866 // simplified.
5867 if (ShAmt->uge(TypeBits))
5868 break;
5869
5870 if (ICI.isEquality()) {
5871 // If we are comparing against bits always shifted out, the
5872 // comparison cannot succeed.
5873 Constant *Comp =
5874 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5875 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5876 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5877 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5878 return ReplaceInstUsesWith(ICI, Cst);
5879 }
5880
5881 if (LHSI->hasOneUse()) {
5882 // Otherwise strength reduce the shift into an and.
5883 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5884 Constant *Mask =
5885 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005886
Chris Lattnera0141b92007-07-15 20:42:37 +00005887 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005888 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005889 Mask, LHSI->getName()+".mask");
5890 Value *And = InsertNewInstBefore(AndI, ICI);
5891 return new ICmpInst(ICI.getPredicate(), And,
5892 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005893 }
5894 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005895
5896 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5897 bool TrueIfSigned = false;
5898 if (LHSI->hasOneUse() &&
5899 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5900 // (X << 31) <s 0 --> (X&1) != 0
5901 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5902 (TypeBits-ShAmt->getZExtValue()-1));
5903 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005904 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005905 Mask, LHSI->getName()+".mask");
5906 Value *And = InsertNewInstBefore(AndI, ICI);
5907
5908 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5909 And, Constant::getNullValue(And->getType()));
5910 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005911 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005912 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005913
5914 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005915 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005916 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005917 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005918 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005919
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005920 // Check that the shift amount is in range. If not, don't perform
5921 // undefined shifts. When the shift is visited it will be
5922 // simplified.
5923 uint32_t TypeBits = RHSV.getBitWidth();
5924 if (ShAmt->uge(TypeBits))
5925 break;
5926
5927 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005928
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005929 // If we are comparing against bits always shifted out, the
5930 // comparison cannot succeed.
5931 APInt Comp = RHSV << ShAmtVal;
5932 if (LHSI->getOpcode() == Instruction::LShr)
5933 Comp = Comp.lshr(ShAmtVal);
5934 else
5935 Comp = Comp.ashr(ShAmtVal);
5936
5937 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5938 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5939 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5940 return ReplaceInstUsesWith(ICI, Cst);
5941 }
5942
5943 // Otherwise, check to see if the bits shifted out are known to be zero.
5944 // If so, we can compare against the unshifted value:
5945 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00005946 if (LHSI->hasOneUse() &&
5947 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005948 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5949 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5950 ConstantExpr::getShl(RHS, ShAmt));
5951 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005952
Evan Chengf30752c2008-04-23 00:38:06 +00005953 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005954 // Otherwise strength reduce the shift into an and.
5955 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5956 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00005957
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005958 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005959 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005960 Mask, LHSI->getName()+".mask");
5961 Value *And = InsertNewInstBefore(AndI, ICI);
5962 return new ICmpInst(ICI.getPredicate(), And,
5963 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005964 }
5965 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005966 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005967
5968 case Instruction::SDiv:
5969 case Instruction::UDiv:
5970 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5971 // Fold this div into the comparison, producing a range check.
5972 // Determine, based on the divide type, what the range is being
5973 // checked. If there is an overflow on the low or high side, remember
5974 // it, otherwise compute the range [low, hi) bounding the new value.
5975 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005976 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5977 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5978 DivRHS))
5979 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005980 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005981
5982 case Instruction::Add:
5983 // Fold: icmp pred (add, X, C1), C2
5984
5985 if (!ICI.isEquality()) {
5986 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5987 if (!LHSC) break;
5988 const APInt &LHSV = LHSC->getValue();
5989
5990 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5991 .subtract(LHSV);
5992
5993 if (ICI.isSignedPredicate()) {
5994 if (CR.getLower().isSignBit()) {
5995 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5996 ConstantInt::get(CR.getUpper()));
5997 } else if (CR.getUpper().isSignBit()) {
5998 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5999 ConstantInt::get(CR.getLower()));
6000 }
6001 } else {
6002 if (CR.getLower().isMinValue()) {
6003 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6004 ConstantInt::get(CR.getUpper()));
6005 } else if (CR.getUpper().isMinValue()) {
6006 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6007 ConstantInt::get(CR.getLower()));
6008 }
6009 }
6010 }
6011 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006012 }
6013
6014 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6015 if (ICI.isEquality()) {
6016 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6017
6018 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6019 // the second operand is a constant, simplify a bit.
6020 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6021 switch (BO->getOpcode()) {
6022 case Instruction::SRem:
6023 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6024 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6025 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6026 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6027 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006028 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006029 BO->getName());
6030 InsertNewInstBefore(NewRem, ICI);
6031 return new ICmpInst(ICI.getPredicate(), NewRem,
6032 Constant::getNullValue(BO->getType()));
6033 }
6034 }
6035 break;
6036 case Instruction::Add:
6037 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6038 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6039 if (BO->hasOneUse())
6040 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6041 Subtract(RHS, BOp1C));
6042 } else if (RHSV == 0) {
6043 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6044 // efficiently invertible, or if the add has just this one use.
6045 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6046
6047 if (Value *NegVal = dyn_castNegVal(BOp1))
6048 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6049 else if (Value *NegVal = dyn_castNegVal(BOp0))
6050 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6051 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006052 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006053 InsertNewInstBefore(Neg, ICI);
6054 Neg->takeName(BO);
6055 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6056 }
6057 }
6058 break;
6059 case Instruction::Xor:
6060 // For the xor case, we can xor two constants together, eliminating
6061 // the explicit xor.
6062 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6063 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6064 ConstantExpr::getXor(RHS, BOC));
6065
6066 // FALLTHROUGH
6067 case Instruction::Sub:
6068 // Replace (([sub|xor] A, B) != 0) with (A != B)
6069 if (RHSV == 0)
6070 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6071 BO->getOperand(1));
6072 break;
6073
6074 case Instruction::Or:
6075 // If bits are being or'd in that are not present in the constant we
6076 // are comparing against, then the comparison could never succeed!
6077 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6078 Constant *NotCI = ConstantExpr::getNot(RHS);
6079 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6080 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6081 isICMP_NE));
6082 }
6083 break;
6084
6085 case Instruction::And:
6086 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6087 // If bits are being compared against that are and'd out, then the
6088 // comparison can never succeed!
6089 if ((RHSV & ~BOC->getValue()) != 0)
6090 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6091 isICMP_NE));
6092
6093 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6094 if (RHS == BOC && RHSV.isPowerOf2())
6095 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6096 ICmpInst::ICMP_NE, LHSI,
6097 Constant::getNullValue(RHS->getType()));
6098
6099 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006100 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006101 Value *X = BO->getOperand(0);
6102 Constant *Zero = Constant::getNullValue(X->getType());
6103 ICmpInst::Predicate pred = isICMP_NE ?
6104 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6105 return new ICmpInst(pred, X, Zero);
6106 }
6107
6108 // ((X & ~7) == 0) --> X < 8
6109 if (RHSV == 0 && isHighOnes(BOC)) {
6110 Value *X = BO->getOperand(0);
6111 Constant *NegX = ConstantExpr::getNeg(BOC);
6112 ICmpInst::Predicate pred = isICMP_NE ?
6113 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6114 return new ICmpInst(pred, X, NegX);
6115 }
6116 }
6117 default: break;
6118 }
6119 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6120 // Handle icmp {eq|ne} <intrinsic>, intcst.
6121 if (II->getIntrinsicID() == Intrinsic::bswap) {
6122 AddToWorkList(II);
6123 ICI.setOperand(0, II->getOperand(1));
6124 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6125 return &ICI;
6126 }
6127 }
6128 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006129 // If the LHS is a cast from an integral value of the same size,
6130 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006131 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6132 Value *CastOp = Cast->getOperand(0);
6133 const Type *SrcTy = CastOp->getType();
6134 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6135 if (SrcTy->isInteger() &&
6136 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6137 // If this is an unsigned comparison, try to make the comparison use
6138 // smaller constant values.
6139 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6140 // X u< 128 => X s> -1
6141 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6142 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6143 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6144 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6145 // X u> 127 => X s< 0
6146 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6147 Constant::getNullValue(SrcTy));
6148 }
6149 }
6150 }
6151 }
6152 return 0;
6153}
6154
6155/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6156/// We only handle extending casts so far.
6157///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006158Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6159 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006160 Value *LHSCIOp = LHSCI->getOperand(0);
6161 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006162 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006163 Value *RHSCIOp;
6164
Chris Lattner8c756c12007-05-05 22:41:33 +00006165 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6166 // integer type is the same size as the pointer type.
6167 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6168 getTargetData().getPointerSizeInBits() ==
6169 cast<IntegerType>(DestTy)->getBitWidth()) {
6170 Value *RHSOp = 0;
6171 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006172 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006173 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6174 RHSOp = RHSC->getOperand(0);
6175 // If the pointer types don't match, insert a bitcast.
6176 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006177 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006178 }
6179
6180 if (RHSOp)
6181 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6182 }
6183
6184 // The code below only handles extension cast instructions, so far.
6185 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006186 if (LHSCI->getOpcode() != Instruction::ZExt &&
6187 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006188 return 0;
6189
Reid Spencere4d87aa2006-12-23 06:05:41 +00006190 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6191 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006192
Reid Spencere4d87aa2006-12-23 06:05:41 +00006193 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006194 // Not an extension from the same type?
6195 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006196 if (RHSCIOp->getType() != LHSCIOp->getType())
6197 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006198
Nick Lewycky4189a532008-01-28 03:48:02 +00006199 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006200 // and the other is a zext), then we can't handle this.
6201 if (CI->getOpcode() != LHSCI->getOpcode())
6202 return 0;
6203
Nick Lewycky4189a532008-01-28 03:48:02 +00006204 // Deal with equality cases early.
6205 if (ICI.isEquality())
6206 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6207
6208 // A signed comparison of sign extended values simplifies into a
6209 // signed comparison.
6210 if (isSignedCmp && isSignedExt)
6211 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6212
6213 // The other three cases all fold into an unsigned comparison.
6214 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006215 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006216
Reid Spencere4d87aa2006-12-23 06:05:41 +00006217 // If we aren't dealing with a constant on the RHS, exit early
6218 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6219 if (!CI)
6220 return 0;
6221
6222 // Compute the constant that would happen if we truncated to SrcTy then
6223 // reextended to DestTy.
6224 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6225 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6226
6227 // If the re-extended constant didn't change...
6228 if (Res2 == CI) {
6229 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6230 // For example, we might have:
6231 // %A = sext short %X to uint
6232 // %B = icmp ugt uint %A, 1330
6233 // It is incorrect to transform this into
6234 // %B = icmp ugt short %X, 1330
6235 // because %A may have negative value.
6236 //
6237 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6238 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006239 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006240 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6241 else
6242 return 0;
6243 }
6244
6245 // The re-extended constant changed so the constant cannot be represented
6246 // in the shorter type. Consequently, we cannot emit a simple comparison.
6247
6248 // First, handle some easy cases. We know the result cannot be equal at this
6249 // point so handle the ICI.isEquality() cases
6250 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006251 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006252 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006253 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006254
6255 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6256 // should have been folded away previously and not enter in here.
6257 Value *Result;
6258 if (isSignedCmp) {
6259 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006260 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006261 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006262 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006263 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006264 } else {
6265 // We're performing an unsigned comparison.
6266 if (isSignedExt) {
6267 // We're performing an unsigned comp with a sign extended value.
6268 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006269 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006270 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6271 NegOne, ICI.getName()), ICI);
6272 } else {
6273 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006274 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006275 }
6276 }
6277
6278 // Finally, return the value computed.
6279 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6280 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6281 return ReplaceInstUsesWith(ICI, Result);
6282 } else {
6283 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6284 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6285 "ICmp should be folded!");
6286 if (Constant *CI = dyn_cast<Constant>(Result))
6287 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6288 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006289 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006290 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006291}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006292
Reid Spencer832254e2007-02-02 02:16:23 +00006293Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6294 return commonShiftTransforms(I);
6295}
6296
6297Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6298 return commonShiftTransforms(I);
6299}
6300
6301Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006302 if (Instruction *R = commonShiftTransforms(I))
6303 return R;
6304
6305 Value *Op0 = I.getOperand(0);
6306
6307 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6308 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6309 if (CSI->isAllOnesValue())
6310 return ReplaceInstUsesWith(I, CSI);
6311
6312 // See if we can turn a signed shr into an unsigned shr.
6313 if (MaskedValueIsZero(Op0,
6314 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006315 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006316
6317 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006318}
6319
6320Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6321 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006322 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006323
6324 // shl X, 0 == X and shr X, 0 == X
6325 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006326 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006327 Op0 == Constant::getNullValue(Op0->getType()))
6328 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006329
Reid Spencere4d87aa2006-12-23 06:05:41 +00006330 if (isa<UndefValue>(Op0)) {
6331 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006332 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006333 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006334 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6335 }
6336 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006337 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6338 return ReplaceInstUsesWith(I, Op0);
6339 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006340 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006341 }
6342
Chris Lattner2eefe512004-04-09 19:05:30 +00006343 // Try to fold constant and into select arguments.
6344 if (isa<Constant>(Op0))
6345 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006346 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006347 return R;
6348
Reid Spencerb83eb642006-10-20 07:07:24 +00006349 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006350 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6351 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006352 return 0;
6353}
6354
Reid Spencerb83eb642006-10-20 07:07:24 +00006355Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006356 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006357 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006358
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006359 // See if we can simplify any instructions used by the instruction whose sole
6360 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006361 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6362 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6363 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006364 KnownZero, KnownOne))
6365 return &I;
6366
Chris Lattner4d5542c2006-01-06 07:12:35 +00006367 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6368 // of a signed value.
6369 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006370 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006371 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006372 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6373 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006374 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006375 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006376 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006377 }
6378
6379 // ((X*C1) << C2) == (X * (C1 << C2))
6380 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6381 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6382 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006383 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006384 ConstantExpr::getShl(BOOp, Op1));
6385
6386 // Try to fold constant and into select arguments.
6387 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6388 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6389 return R;
6390 if (isa<PHINode>(Op0))
6391 if (Instruction *NV = FoldOpIntoPhi(I))
6392 return NV;
6393
Chris Lattner8999dd32007-12-22 09:07:47 +00006394 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6395 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6396 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6397 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6398 // place. Don't try to do this transformation in this case. Also, we
6399 // require that the input operand is a shift-by-constant so that we have
6400 // confidence that the shifts will get folded together. We could do this
6401 // xform in more cases, but it is unlikely to be profitable.
6402 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6403 isa<ConstantInt>(TrOp->getOperand(1))) {
6404 // Okay, we'll do this xform. Make the shift of shift.
6405 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006406 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006407 I.getName());
6408 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6409
6410 // For logical shifts, the truncation has the effect of making the high
6411 // part of the register be zeros. Emulate this by inserting an AND to
6412 // clear the top bits as needed. This 'and' will usually be zapped by
6413 // other xforms later if dead.
6414 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6415 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6416 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6417
6418 // The mask we constructed says what the trunc would do if occurring
6419 // between the shifts. We want to know the effect *after* the second
6420 // shift. We know that it is a logical shift by a constant, so adjust the
6421 // mask as appropriate.
6422 if (I.getOpcode() == Instruction::Shl)
6423 MaskV <<= Op1->getZExtValue();
6424 else {
6425 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6426 MaskV = MaskV.lshr(Op1->getZExtValue());
6427 }
6428
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006429 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006430 TI->getName());
6431 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6432
6433 // Return the value truncated to the interesting size.
6434 return new TruncInst(And, I.getType());
6435 }
6436 }
6437
Chris Lattner4d5542c2006-01-06 07:12:35 +00006438 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006439 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6440 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6441 Value *V1, *V2;
6442 ConstantInt *CC;
6443 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006444 default: break;
6445 case Instruction::Add:
6446 case Instruction::And:
6447 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006448 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006449 // These operators commute.
6450 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006451 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6452 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006453 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006454 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006455 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006456 Op0BO->getName());
6457 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006458 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006459 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006460 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006461 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006462 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006463 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006464 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006465 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006466
Chris Lattner150f12a2005-09-18 06:30:59 +00006467 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006468 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006469 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006470 match(Op0BOOp1,
6471 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006472 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6473 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006474 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006475 Op0BO->getOperand(0), Op1,
6476 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006477 InsertNewInstBefore(YS, I); // (Y << C)
6478 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006479 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006480 V1->getName()+".mask");
6481 InsertNewInstBefore(XM, I); // X & (CC << C)
6482
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006483 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006484 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006485 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006486
Reid Spencera07cb7d2007-02-02 14:41:37 +00006487 // FALL THROUGH.
6488 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006489 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006490 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6491 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006492 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006493 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006494 Op0BO->getOperand(1), Op1,
6495 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006496 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006497 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006498 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006499 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006500 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006501 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006502 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006503 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006504 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006505
Chris Lattner13d4ab42006-05-31 21:14:00 +00006506 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006507 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6508 match(Op0BO->getOperand(0),
6509 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006510 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006511 cast<BinaryOperator>(Op0BO->getOperand(0))
6512 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006513 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006514 Op0BO->getOperand(1), Op1,
6515 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006516 InsertNewInstBefore(YS, I); // (Y << C)
6517 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006518 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006519 V1->getName()+".mask");
6520 InsertNewInstBefore(XM, I); // X & (CC << C)
6521
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006522 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006523 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006524
Chris Lattner11021cb2005-09-18 05:12:10 +00006525 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006526 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006527 }
6528
6529
6530 // If the operand is an bitwise operator with a constant RHS, and the
6531 // shift is the only use, we can pull it out of the shift.
6532 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6533 bool isValid = true; // Valid only for And, Or, Xor
6534 bool highBitSet = false; // Transform if high bit of constant set?
6535
6536 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006537 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006538 case Instruction::Add:
6539 isValid = isLeftShift;
6540 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006541 case Instruction::Or:
6542 case Instruction::Xor:
6543 highBitSet = false;
6544 break;
6545 case Instruction::And:
6546 highBitSet = true;
6547 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006548 }
6549
6550 // If this is a signed shift right, and the high bit is modified
6551 // by the logical operation, do not perform the transformation.
6552 // The highBitSet boolean indicates the value of the high bit of
6553 // the constant which would cause it to be modified for this
6554 // operation.
6555 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006556 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006557 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006558
6559 if (isValid) {
6560 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6561
6562 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006563 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006564 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006565 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006566
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006567 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006568 NewRHS);
6569 }
6570 }
6571 }
6572 }
6573
Chris Lattnerad0124c2006-01-06 07:52:12 +00006574 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006575 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6576 if (ShiftOp && !ShiftOp->isShift())
6577 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006578
Reid Spencerb83eb642006-10-20 07:07:24 +00006579 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006580 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006581 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6582 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006583 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6584 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6585 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006586
Zhou Sheng4351c642007-04-02 08:20:41 +00006587 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006588 if (AmtSum > TypeBits)
6589 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006590
6591 const IntegerType *Ty = cast<IntegerType>(I.getType());
6592
6593 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006594 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006595 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006596 ConstantInt::get(Ty, AmtSum));
6597 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6598 I.getOpcode() == Instruction::AShr) {
6599 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006600 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006601 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6602 I.getOpcode() == Instruction::LShr) {
6603 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6604 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006605 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006606 InsertNewInstBefore(Shift, I);
6607
Zhou Shenge9e03f62007-03-28 15:02:20 +00006608 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006609 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006610 }
6611
Chris Lattnerb87056f2007-02-05 00:57:54 +00006612 // Okay, if we get here, one shift must be left, and the other shift must be
6613 // right. See if the amounts are equal.
6614 if (ShiftAmt1 == ShiftAmt2) {
6615 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6616 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006617 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006618 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006619 }
6620 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6621 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006622 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006623 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006624 }
6625 // We can simplify ((X << C) >>s C) into a trunc + sext.
6626 // NOTE: we could do this for any C, but that would make 'unusual' integer
6627 // types. For now, just stick to ones well-supported by the code
6628 // generators.
6629 const Type *SExtType = 0;
6630 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006631 case 1 :
6632 case 8 :
6633 case 16 :
6634 case 32 :
6635 case 64 :
6636 case 128:
6637 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6638 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006639 default: break;
6640 }
6641 if (SExtType) {
6642 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6643 InsertNewInstBefore(NewTrunc, I);
6644 return new SExtInst(NewTrunc, Ty);
6645 }
6646 // Otherwise, we can't handle it yet.
6647 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006648 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006649
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006650 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006651 if (I.getOpcode() == Instruction::Shl) {
6652 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6653 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006654 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006655 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006656 InsertNewInstBefore(Shift, I);
6657
Reid Spencer55702aa2007-03-25 21:11:44 +00006658 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006659 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006660 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006661
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006662 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006663 if (I.getOpcode() == Instruction::LShr) {
6664 assert(ShiftOp->getOpcode() == Instruction::Shl);
6665 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006666 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006667 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006668
Reid Spencerd5e30f02007-03-26 17:18:58 +00006669 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006670 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006671 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006672
6673 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6674 } else {
6675 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006676 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006677
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006678 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006679 if (I.getOpcode() == Instruction::Shl) {
6680 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6681 ShiftOp->getOpcode() == Instruction::AShr);
6682 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006683 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006684 ConstantInt::get(Ty, ShiftDiff));
6685 InsertNewInstBefore(Shift, I);
6686
Reid Spencer55702aa2007-03-25 21:11:44 +00006687 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006688 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006689 }
6690
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006691 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006692 if (I.getOpcode() == Instruction::LShr) {
6693 assert(ShiftOp->getOpcode() == Instruction::Shl);
6694 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006695 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006696 InsertNewInstBefore(Shift, I);
6697
Reid Spencer68d27cf2007-03-26 23:45:51 +00006698 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006699 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006700 }
6701
6702 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006703 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006704 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006705 return 0;
6706}
6707
Chris Lattnera1be5662002-05-02 17:06:02 +00006708
Chris Lattnercfd65102005-10-29 04:36:15 +00006709/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6710/// expression. If so, decompose it, returning some value X, such that Val is
6711/// X*Scale+Offset.
6712///
6713static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006714 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006715 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006716 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006717 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006718 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006719 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006720 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6721 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6722 if (I->getOpcode() == Instruction::Shl) {
6723 // This is a value scaled by '1 << the shift amt'.
6724 Scale = 1U << RHS->getZExtValue();
6725 Offset = 0;
6726 return I->getOperand(0);
6727 } else if (I->getOpcode() == Instruction::Mul) {
6728 // This value is scaled by 'RHS'.
6729 Scale = RHS->getZExtValue();
6730 Offset = 0;
6731 return I->getOperand(0);
6732 } else if (I->getOpcode() == Instruction::Add) {
6733 // We have X+C. Check to see if we really have (X*C2)+C1,
6734 // where C1 is divisible by C2.
6735 unsigned SubScale;
6736 Value *SubVal =
6737 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6738 Offset += RHS->getZExtValue();
6739 Scale = SubScale;
6740 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006741 }
6742 }
6743 }
6744
6745 // Otherwise, we can't look past this.
6746 Scale = 1;
6747 Offset = 0;
6748 return Val;
6749}
6750
6751
Chris Lattnerb3f83972005-10-24 06:03:58 +00006752/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6753/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006754Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006755 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006756 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006757
Chris Lattnerb53c2382005-10-24 06:22:12 +00006758 // Remove any uses of AI that are dead.
6759 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006760
Chris Lattnerb53c2382005-10-24 06:22:12 +00006761 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6762 Instruction *User = cast<Instruction>(*UI++);
6763 if (isInstructionTriviallyDead(User)) {
6764 while (UI != E && *UI == User)
6765 ++UI; // If this instruction uses AI more than once, don't break UI.
6766
Chris Lattnerb53c2382005-10-24 06:22:12 +00006767 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006768 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006769 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006770 }
6771 }
6772
Chris Lattnerb3f83972005-10-24 06:03:58 +00006773 // Get the type really allocated and the type casted to.
6774 const Type *AllocElTy = AI.getAllocatedType();
6775 const Type *CastElTy = PTy->getElementType();
6776 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006777
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006778 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6779 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006780 if (CastElTyAlign < AllocElTyAlign) return 0;
6781
Chris Lattner39387a52005-10-24 06:35:18 +00006782 // If the allocation has multiple uses, only promote it if we are strictly
6783 // increasing the alignment of the resultant allocation. If we keep it the
6784 // same, we open the door to infinite loops of various kinds.
6785 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6786
Duncan Sands514ab342007-11-01 20:53:16 +00006787 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6788 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006789 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006790
Chris Lattner455fcc82005-10-29 03:19:53 +00006791 // See if we can satisfy the modulus by pulling a scale out of the array
6792 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006793 unsigned ArraySizeScale;
6794 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006795 Value *NumElements = // See if the array size is a decomposable linear expr.
6796 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6797
Chris Lattner455fcc82005-10-29 03:19:53 +00006798 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6799 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006800 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6801 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006802
Chris Lattner455fcc82005-10-29 03:19:53 +00006803 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6804 Value *Amt = 0;
6805 if (Scale == 1) {
6806 Amt = NumElements;
6807 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006808 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006809 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6810 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006811 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006812 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006813 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006814 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00006815 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006816 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006817 }
6818
Jeff Cohen86796be2007-04-04 16:58:57 +00006819 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6820 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006821 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00006822 Amt = InsertNewInstBefore(Tmp, AI);
6823 }
6824
Chris Lattnerb3f83972005-10-24 06:03:58 +00006825 AllocationInst *New;
6826 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006827 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006828 else
Chris Lattner6934a042007-02-11 01:23:03 +00006829 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006830 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006831 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006832
6833 // If the allocation has multiple uses, insert a cast and change all things
6834 // that used it to use the new cast. This will also hack on CI, but it will
6835 // die soon.
6836 if (!AI.hasOneUse()) {
6837 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006838 // New is the allocation instruction, pointer typed. AI is the original
6839 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6840 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006841 InsertNewInstBefore(NewCast, AI);
6842 AI.replaceAllUsesWith(NewCast);
6843 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006844 return ReplaceInstUsesWith(CI, New);
6845}
6846
Chris Lattner70074e02006-05-13 02:06:03 +00006847/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006848/// and return it as type Ty without inserting any new casts and without
6849/// changing the computed value. This is used by code that tries to decide
6850/// whether promoting or shrinking integer operations to wider or smaller types
6851/// will allow us to eliminate a truncate or extend.
6852///
6853/// This is a truncation operation if Ty is smaller than V->getType(), or an
6854/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00006855bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6856 unsigned CastOpc,
6857 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006858 // We can always evaluate constants in another type.
6859 if (isa<ConstantInt>(V))
6860 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006861
6862 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006863 if (!I) return false;
6864
6865 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006866
Chris Lattner951626b2007-08-02 06:11:14 +00006867 // If this is an extension or truncate, we can often eliminate it.
6868 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6869 // If this is a cast from the destination type, we can trivially eliminate
6870 // it, and this will remove a cast overall.
6871 if (I->getOperand(0)->getType() == Ty) {
6872 // If the first operand is itself a cast, and is eliminable, do not count
6873 // this as an eliminable cast. We would prefer to eliminate those two
6874 // casts first.
6875 if (!isa<CastInst>(I->getOperand(0)))
6876 ++NumCastsRemoved;
6877 return true;
6878 }
6879 }
6880
6881 // We can't extend or shrink something that has multiple uses: doing so would
6882 // require duplicating the instruction in general, which isn't profitable.
6883 if (!I->hasOneUse()) return false;
6884
Chris Lattner70074e02006-05-13 02:06:03 +00006885 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006886 case Instruction::Add:
6887 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006888 case Instruction::And:
6889 case Instruction::Or:
6890 case Instruction::Xor:
6891 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006892 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6893 NumCastsRemoved) &&
6894 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6895 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006896
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006897 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006898 // A multiply can be truncated by truncating its operands.
6899 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6900 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6901 NumCastsRemoved) &&
6902 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6903 NumCastsRemoved);
6904
Chris Lattner46b96052006-11-29 07:18:39 +00006905 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006906 // If we are truncating the result of this SHL, and if it's a shift of a
6907 // constant amount, we can always perform a SHL in a smaller type.
6908 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006909 uint32_t BitWidth = Ty->getBitWidth();
6910 if (BitWidth < OrigTy->getBitWidth() &&
6911 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006912 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6913 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006914 }
6915 break;
6916 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006917 // If this is a truncate of a logical shr, we can truncate it to a smaller
6918 // lshr iff we know that the bits we would otherwise be shifting in are
6919 // already zeros.
6920 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006921 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6922 uint32_t BitWidth = Ty->getBitWidth();
6923 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006924 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006925 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6926 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006927 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6928 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006929 }
6930 }
Chris Lattner46b96052006-11-29 07:18:39 +00006931 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006932 case Instruction::ZExt:
6933 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006934 case Instruction::Trunc:
6935 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006936 // can safely replace it. Note that replacing it does not reduce the number
6937 // of casts in the input.
6938 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006939 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006940
Reid Spencer3da59db2006-11-27 01:05:10 +00006941 break;
6942 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006943 // TODO: Can handle more cases here.
6944 break;
6945 }
6946
6947 return false;
6948}
6949
6950/// EvaluateInDifferentType - Given an expression that
6951/// CanEvaluateInDifferentType returns true for, actually insert the code to
6952/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006953Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006954 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006955 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006956 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006957
6958 // Otherwise, it must be an instruction.
6959 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006960 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006961 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006962 case Instruction::Add:
6963 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006964 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006965 case Instruction::And:
6966 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006967 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006968 case Instruction::AShr:
6969 case Instruction::LShr:
6970 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006971 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006972 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006973 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00006974 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006975 break;
6976 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006977 case Instruction::Trunc:
6978 case Instruction::ZExt:
6979 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006980 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006981 // just return the source. There's no need to insert it because it is not
6982 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006983 if (I->getOperand(0)->getType() == Ty)
6984 return I->getOperand(0);
6985
Chris Lattner951626b2007-08-02 06:11:14 +00006986 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006987 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00006988 Ty, I->getName());
6989 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006990 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006991 // TODO: Can handle more cases here.
6992 assert(0 && "Unreachable!");
6993 break;
6994 }
6995
6996 return InsertNewInstBefore(Res, *I);
6997}
6998
Reid Spencer3da59db2006-11-27 01:05:10 +00006999/// @brief Implement the transforms common to all CastInst visitors.
7000Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007001 Value *Src = CI.getOperand(0);
7002
Dan Gohman23d9d272007-05-11 21:10:54 +00007003 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007004 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007005 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007006 if (Instruction::CastOps opc =
7007 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7008 // The first cast (CSrc) is eliminable so we need to fix up or replace
7009 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007010 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007011 }
7012 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007013
Reid Spencer3da59db2006-11-27 01:05:10 +00007014 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007015 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7016 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7017 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007018
7019 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007020 if (isa<PHINode>(Src))
7021 if (Instruction *NV = FoldOpIntoPhi(CI))
7022 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007023
Reid Spencer3da59db2006-11-27 01:05:10 +00007024 return 0;
7025}
7026
Chris Lattnerd3e28342007-04-27 17:44:50 +00007027/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7028Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7029 Value *Src = CI.getOperand(0);
7030
Chris Lattnerd3e28342007-04-27 17:44:50 +00007031 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007032 // If casting the result of a getelementptr instruction with no offset, turn
7033 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007034 if (GEP->hasAllZeroIndices()) {
7035 // Changing the cast operand is usually not a good idea but it is safe
7036 // here because the pointer operand is being replaced with another
7037 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007038 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007039 CI.setOperand(0, GEP->getOperand(0));
7040 return &CI;
7041 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007042
7043 // If the GEP has a single use, and the base pointer is a bitcast, and the
7044 // GEP computes a constant offset, see if we can convert these three
7045 // instructions into fewer. This typically happens with unions and other
7046 // non-type-safe code.
7047 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7048 if (GEP->hasAllConstantIndices()) {
7049 // We are guaranteed to get a constant from EmitGEPOffset.
7050 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7051 int64_t Offset = OffsetV->getSExtValue();
7052
7053 // Get the base pointer input of the bitcast, and the type it points to.
7054 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7055 const Type *GEPIdxTy =
7056 cast<PointerType>(OrigBase->getType())->getElementType();
7057 if (GEPIdxTy->isSized()) {
7058 SmallVector<Value*, 8> NewIndices;
7059
Chris Lattnerc42e2262007-05-05 01:59:31 +00007060 // Start with the index over the outer type. Note that the type size
7061 // might be zero (even if the offset isn't zero) if the indexed type
7062 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007063 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007064 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007065 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007066 FirstIdx = Offset/TySize;
7067 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007068
Chris Lattnerc42e2262007-05-05 01:59:31 +00007069 // Handle silly modulus not returning values values [0..TySize).
7070 if (Offset < 0) {
7071 --FirstIdx;
7072 Offset += TySize;
7073 assert(Offset >= 0);
7074 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007075 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007076 }
7077
7078 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007079
7080 // Index into the types. If we fail, set OrigBase to null.
7081 while (Offset) {
7082 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7083 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007084 if (Offset < (int64_t)SL->getSizeInBytes()) {
7085 unsigned Elt = SL->getElementContainingOffset(Offset);
7086 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007087
Chris Lattner6b6aef82007-05-15 00:16:00 +00007088 Offset -= SL->getElementOffset(Elt);
7089 GEPIdxTy = STy->getElementType(Elt);
7090 } else {
7091 // Otherwise, we can't index into this, bail out.
7092 Offset = 0;
7093 OrigBase = 0;
7094 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007095 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7096 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007097 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007098 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7099 Offset %= EltSize;
7100 } else {
7101 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7102 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007103 GEPIdxTy = STy->getElementType();
7104 } else {
7105 // Otherwise, we can't index into this, bail out.
7106 Offset = 0;
7107 OrigBase = 0;
7108 }
7109 }
7110 if (OrigBase) {
7111 // If we were able to index down into an element, create the GEP
7112 // and bitcast the result. This eliminates one bitcast, potentially
7113 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007114 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7115 NewIndices.begin(),
7116 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007117 InsertNewInstBefore(NGEP, CI);
7118 NGEP->takeName(GEP);
7119
Chris Lattner9bc14642007-04-28 00:57:34 +00007120 if (isa<BitCastInst>(CI))
7121 return new BitCastInst(NGEP, CI.getType());
7122 assert(isa<PtrToIntInst>(CI));
7123 return new PtrToIntInst(NGEP, CI.getType());
7124 }
7125 }
7126 }
7127 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007128 }
7129
7130 return commonCastTransforms(CI);
7131}
7132
7133
7134
Chris Lattnerc739cd62007-03-03 05:27:34 +00007135/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7136/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007137/// cases.
7138/// @brief Implement the transforms common to CastInst with integer operands
7139Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7140 if (Instruction *Result = commonCastTransforms(CI))
7141 return Result;
7142
7143 Value *Src = CI.getOperand(0);
7144 const Type *SrcTy = Src->getType();
7145 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007146 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7147 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007148
Reid Spencer3da59db2006-11-27 01:05:10 +00007149 // See if we can simplify any instructions used by the LHS whose sole
7150 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007151 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7152 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007153 KnownZero, KnownOne))
7154 return &CI;
7155
7156 // If the source isn't an instruction or has more than one use then we
7157 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007158 Instruction *SrcI = dyn_cast<Instruction>(Src);
7159 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007160 return 0;
7161
Chris Lattnerc739cd62007-03-03 05:27:34 +00007162 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007163 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007164 if (!isa<BitCastInst>(CI) &&
7165 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007166 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007167 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007168 // eliminates the cast, so it is always a win. If this is a zero-extension,
7169 // we need to do an AND to maintain the clear top-part of the computation,
7170 // so we require that the input have eliminated at least one cast. If this
7171 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007172 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007173 bool DoXForm;
7174 switch (CI.getOpcode()) {
7175 default:
7176 // All the others use floating point so we shouldn't actually
7177 // get here because of the check above.
7178 assert(0 && "Unknown cast type");
7179 case Instruction::Trunc:
7180 DoXForm = true;
7181 break;
7182 case Instruction::ZExt:
7183 DoXForm = NumCastsRemoved >= 1;
7184 break;
7185 case Instruction::SExt:
7186 DoXForm = NumCastsRemoved >= 2;
7187 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007188 }
7189
7190 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007191 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7192 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007193 assert(Res->getType() == DestTy);
7194 switch (CI.getOpcode()) {
7195 default: assert(0 && "Unknown cast type!");
7196 case Instruction::Trunc:
7197 case Instruction::BitCast:
7198 // Just replace this cast with the result.
7199 return ReplaceInstUsesWith(CI, Res);
7200 case Instruction::ZExt: {
7201 // We need to emit an AND to clear the high bits.
7202 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007203 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7204 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007205 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007206 }
7207 case Instruction::SExt:
7208 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007209 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007210 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7211 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007212 }
7213 }
7214 }
7215
7216 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7217 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7218
7219 switch (SrcI->getOpcode()) {
7220 case Instruction::Add:
7221 case Instruction::Mul:
7222 case Instruction::And:
7223 case Instruction::Or:
7224 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007225 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007226 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7227 // Don't insert two casts if they cannot be eliminated. We allow
7228 // two casts to be inserted if the sizes are the same. This could
7229 // only be converting signedness, which is a noop.
7230 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007231 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7232 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007233 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007234 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7235 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007236 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007237 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007238 }
7239 }
7240
7241 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7242 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7243 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007244 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007245 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007246 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007247 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007248 }
7249 break;
7250 case Instruction::SDiv:
7251 case Instruction::UDiv:
7252 case Instruction::SRem:
7253 case Instruction::URem:
7254 // If we are just changing the sign, rewrite.
7255 if (DestBitSize == SrcBitSize) {
7256 // Don't insert two casts if they cannot be eliminated. We allow
7257 // two casts to be inserted if the sizes are the same. This could
7258 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007259 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7260 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007261 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7262 Op0, DestTy, SrcI);
7263 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7264 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007265 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007266 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7267 }
7268 }
7269 break;
7270
7271 case Instruction::Shl:
7272 // Allow changing the sign of the source operand. Do not allow
7273 // changing the size of the shift, UNLESS the shift amount is a
7274 // constant. We must not change variable sized shifts to a smaller
7275 // size, because it is undefined to shift more bits out than exist
7276 // in the value.
7277 if (DestBitSize == SrcBitSize ||
7278 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007279 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7280 Instruction::BitCast : Instruction::Trunc);
7281 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007282 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007283 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007284 }
7285 break;
7286 case Instruction::AShr:
7287 // If this is a signed shr, and if all bits shifted in are about to be
7288 // truncated off, turn it into an unsigned shr to allow greater
7289 // simplifications.
7290 if (DestBitSize < SrcBitSize &&
7291 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007292 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007293 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7294 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007295 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007296 }
7297 }
7298 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007299 }
7300 return 0;
7301}
7302
Chris Lattner8a9f5712007-04-11 06:57:46 +00007303Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007304 if (Instruction *Result = commonIntCastTransforms(CI))
7305 return Result;
7306
7307 Value *Src = CI.getOperand(0);
7308 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007309 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7310 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007311
7312 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7313 switch (SrcI->getOpcode()) {
7314 default: break;
7315 case Instruction::LShr:
7316 // We can shrink lshr to something smaller if we know the bits shifted in
7317 // are already zeros.
7318 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007319 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007320
7321 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007322 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007323 Value* SrcIOp0 = SrcI->getOperand(0);
7324 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007325 if (ShAmt >= DestBitWidth) // All zeros.
7326 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7327
7328 // Okay, we can shrink this. Truncate the input, then return a new
7329 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007330 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7331 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7332 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007333 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007334 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007335 } else { // This is a variable shr.
7336
7337 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7338 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7339 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007340 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007341 Value *One = ConstantInt::get(SrcI->getType(), 1);
7342
Reid Spencer832254e2007-02-02 02:16:23 +00007343 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007344 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007345 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007346 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007347 SrcI->getOperand(0),
7348 "tmp"), CI);
7349 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007350 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007351 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007352 }
7353 break;
7354 }
7355 }
7356
7357 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007358}
7359
Evan Chengb98a10e2008-03-24 00:21:34 +00007360/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7361/// in order to eliminate the icmp.
7362Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7363 bool DoXform) {
7364 // If we are just checking for a icmp eq of a single bit and zext'ing it
7365 // to an integer, then shift the bit to the appropriate place and then
7366 // cast to integer to avoid the comparison.
7367 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7368 const APInt &Op1CV = Op1C->getValue();
7369
7370 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7371 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7372 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7373 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7374 if (!DoXform) return ICI;
7375
7376 Value *In = ICI->getOperand(0);
7377 Value *Sh = ConstantInt::get(In->getType(),
7378 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007379 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007380 In->getName()+".lobit"),
7381 CI);
7382 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007383 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007384 false/*ZExt*/, "tmp", &CI);
7385
7386 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7387 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007388 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007389 In->getName()+".not"),
7390 CI);
7391 }
7392
7393 return ReplaceInstUsesWith(CI, In);
7394 }
7395
7396
7397
7398 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7399 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7400 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7401 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7402 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7403 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7404 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7405 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7406 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7407 // This only works for EQ and NE
7408 ICI->isEquality()) {
7409 // If Op1C some other power of two, convert:
7410 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7411 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7412 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7413 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7414
7415 APInt KnownZeroMask(~KnownZero);
7416 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7417 if (!DoXform) return ICI;
7418
7419 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7420 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7421 // (X&4) == 2 --> false
7422 // (X&4) != 2 --> true
7423 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7424 Res = ConstantExpr::getZExt(Res, CI.getType());
7425 return ReplaceInstUsesWith(CI, Res);
7426 }
7427
7428 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7429 Value *In = ICI->getOperand(0);
7430 if (ShiftAmt) {
7431 // Perform a logical shr by shiftamt.
7432 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007433 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007434 ConstantInt::get(In->getType(), ShiftAmt),
7435 In->getName()+".lobit"), CI);
7436 }
7437
7438 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7439 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007440 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007441 InsertNewInstBefore(cast<Instruction>(In), CI);
7442 }
7443
7444 if (CI.getType() == In->getType())
7445 return ReplaceInstUsesWith(CI, In);
7446 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007447 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007448 }
7449 }
7450 }
7451
7452 return 0;
7453}
7454
Chris Lattner8a9f5712007-04-11 06:57:46 +00007455Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007456 // If one of the common conversion will work ..
7457 if (Instruction *Result = commonIntCastTransforms(CI))
7458 return Result;
7459
7460 Value *Src = CI.getOperand(0);
7461
7462 // If this is a cast of a cast
7463 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007464 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7465 // types and if the sizes are just right we can convert this into a logical
7466 // 'and' which will be much cheaper than the pair of casts.
7467 if (isa<TruncInst>(CSrc)) {
7468 // Get the sizes of the types involved
7469 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007470 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7471 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7472 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007473 // If we're actually extending zero bits and the trunc is a no-op
7474 if (MidSize < DstSize && SrcSize == DstSize) {
7475 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007476 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007477 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007478 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007479 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007480 // Unfortunately, if the type changed, we need to cast it back.
7481 if (And->getType() != CI.getType()) {
7482 And->setName(CSrc->getName()+".mask");
7483 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007484 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007485 }
7486 return And;
7487 }
7488 }
7489 }
7490
Evan Chengb98a10e2008-03-24 00:21:34 +00007491 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7492 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007493
Evan Chengb98a10e2008-03-24 00:21:34 +00007494 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7495 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7496 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7497 // of the (zext icmp) will be transformed.
7498 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7499 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7500 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7501 (transformZExtICmp(LHS, CI, false) ||
7502 transformZExtICmp(RHS, CI, false))) {
7503 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7504 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007505 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007506 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007507 }
7508
Reid Spencer3da59db2006-11-27 01:05:10 +00007509 return 0;
7510}
7511
Chris Lattner8a9f5712007-04-11 06:57:46 +00007512Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007513 if (Instruction *I = commonIntCastTransforms(CI))
7514 return I;
7515
Chris Lattner8a9f5712007-04-11 06:57:46 +00007516 Value *Src = CI.getOperand(0);
7517
7518 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7519 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7520 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7521 // If we are just checking for a icmp eq of a single bit and zext'ing it
7522 // to an integer, then shift the bit to the appropriate place and then
7523 // cast to integer to avoid the comparison.
7524 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7525 const APInt &Op1CV = Op1C->getValue();
7526
7527 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7528 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7529 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7530 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7531 Value *In = ICI->getOperand(0);
7532 Value *Sh = ConstantInt::get(In->getType(),
7533 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007534 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007535 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007536 CI);
7537 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007538 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007539 true/*SExt*/, "tmp", &CI);
7540
7541 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007542 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007543 In->getName()+".not"), CI);
7544
7545 return ReplaceInstUsesWith(CI, In);
7546 }
7547 }
7548 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00007549
7550 // See if the value being truncated is already sign extended. If so, just
7551 // eliminate the trunc/sext pair.
7552 if (getOpcode(Src) == Instruction::Trunc) {
7553 Value *Op = cast<User>(Src)->getOperand(0);
7554 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7555 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7556 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7557 unsigned NumSignBits = ComputeNumSignBits(Op);
7558
7559 if (OpBits == DestBits) {
7560 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7561 // bits, it is already ready.
7562 if (NumSignBits > DestBits-MidBits)
7563 return ReplaceInstUsesWith(CI, Op);
7564 } else if (OpBits < DestBits) {
7565 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7566 // bits, just sext from i32.
7567 if (NumSignBits > OpBits-MidBits)
7568 return new SExtInst(Op, CI.getType(), "tmp");
7569 } else {
7570 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7571 // bits, just truncate to i32.
7572 if (NumSignBits > OpBits-MidBits)
7573 return new TruncInst(Op, CI.getType(), "tmp");
7574 }
7575 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00007576
Chris Lattnerba417832007-04-11 06:12:58 +00007577 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007578}
7579
Chris Lattnerb7530652008-01-27 05:29:54 +00007580/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7581/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007582static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007583 APFloat F = CFP->getValueAPF();
7584 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007585 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007586 return 0;
7587}
7588
7589/// LookThroughFPExtensions - If this is an fp extension instruction, look
7590/// through it until we get the source value.
7591static Value *LookThroughFPExtensions(Value *V) {
7592 if (Instruction *I = dyn_cast<Instruction>(V))
7593 if (I->getOpcode() == Instruction::FPExt)
7594 return LookThroughFPExtensions(I->getOperand(0));
7595
7596 // If this value is a constant, return the constant in the smallest FP type
7597 // that can accurately represent it. This allows us to turn
7598 // (float)((double)X+2.0) into x+2.0f.
7599 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7600 if (CFP->getType() == Type::PPC_FP128Ty)
7601 return V; // No constant folding of this.
7602 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007603 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007604 return V;
7605 if (CFP->getType() == Type::DoubleTy)
7606 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007607 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007608 return V;
7609 // Don't try to shrink to various long double types.
7610 }
7611
7612 return V;
7613}
7614
7615Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7616 if (Instruction *I = commonCastTransforms(CI))
7617 return I;
7618
7619 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7620 // smaller than the destination type, we can eliminate the truncate by doing
7621 // the add as the smaller type. This applies to add/sub/mul/div as well as
7622 // many builtins (sqrt, etc).
7623 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7624 if (OpI && OpI->hasOneUse()) {
7625 switch (OpI->getOpcode()) {
7626 default: break;
7627 case Instruction::Add:
7628 case Instruction::Sub:
7629 case Instruction::Mul:
7630 case Instruction::FDiv:
7631 case Instruction::FRem:
7632 const Type *SrcTy = OpI->getType();
7633 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7634 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7635 if (LHSTrunc->getType() != SrcTy &&
7636 RHSTrunc->getType() != SrcTy) {
7637 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7638 // If the source types were both smaller than the destination type of
7639 // the cast, do this xform.
7640 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7641 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7642 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7643 CI.getType(), CI);
7644 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7645 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007646 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007647 }
7648 }
7649 break;
7650 }
7651 }
7652 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007653}
7654
7655Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7656 return commonCastTransforms(CI);
7657}
7658
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007659Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7660 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7661 // mantissa to accurately represent all values of X. For example, do not
7662 // do this with i64->float->i64.
7663 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7664 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7665 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00007666 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007667 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7668
7669 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007670}
7671
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007672Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7673 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7674 // mantissa to accurately represent all values of X. For example, do not
7675 // do this with i64->float->i64.
7676 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7677 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7678 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00007679 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007680 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7681
7682 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007683}
7684
7685Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7686 return commonCastTransforms(CI);
7687}
7688
7689Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7690 return commonCastTransforms(CI);
7691}
7692
7693Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007694 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007695}
7696
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007697Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7698 if (Instruction *I = commonCastTransforms(CI))
7699 return I;
7700
7701 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7702 if (!DestPointee->isSized()) return 0;
7703
7704 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7705 ConstantInt *Cst;
7706 Value *X;
7707 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7708 m_ConstantInt(Cst)))) {
7709 // If the source and destination operands have the same type, see if this
7710 // is a single-index GEP.
7711 if (X->getType() == CI.getType()) {
7712 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007713 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007714
7715 // Convert the constant to intptr type.
7716 APInt Offset = Cst->getValue();
7717 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7718
7719 // If Offset is evenly divisible by Size, we can do this xform.
7720 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7721 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007722 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007723 }
7724 }
7725 // TODO: Could handle other cases, e.g. where add is indexing into field of
7726 // struct etc.
7727 } else if (CI.getOperand(0)->hasOneUse() &&
7728 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7729 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7730 // "inttoptr+GEP" instead of "add+intptr".
7731
7732 // Get the size of the pointee type.
7733 uint64_t Size = TD->getABITypeSize(DestPointee);
7734
7735 // Convert the constant to intptr type.
7736 APInt Offset = Cst->getValue();
7737 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7738
7739 // If Offset is evenly divisible by Size, we can do this xform.
7740 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7741 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7742
7743 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7744 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007745 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007746 }
7747 }
7748 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007749}
7750
Chris Lattnerd3e28342007-04-27 17:44:50 +00007751Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007752 // If the operands are integer typed then apply the integer transforms,
7753 // otherwise just apply the common ones.
7754 Value *Src = CI.getOperand(0);
7755 const Type *SrcTy = Src->getType();
7756 const Type *DestTy = CI.getType();
7757
Chris Lattner42a75512007-01-15 02:27:26 +00007758 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007759 if (Instruction *Result = commonIntCastTransforms(CI))
7760 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007761 } else if (isa<PointerType>(SrcTy)) {
7762 if (Instruction *I = commonPointerCastTransforms(CI))
7763 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007764 } else {
7765 if (Instruction *Result = commonCastTransforms(CI))
7766 return Result;
7767 }
7768
7769
7770 // Get rid of casts from one type to the same type. These are useless and can
7771 // be replaced by the operand.
7772 if (DestTy == Src->getType())
7773 return ReplaceInstUsesWith(CI, Src);
7774
Reid Spencer3da59db2006-11-27 01:05:10 +00007775 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007776 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7777 const Type *DstElTy = DstPTy->getElementType();
7778 const Type *SrcElTy = SrcPTy->getElementType();
7779
Nate Begeman83ad90a2008-03-31 00:22:16 +00007780 // If the address spaces don't match, don't eliminate the bitcast, which is
7781 // required for changing types.
7782 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7783 return 0;
7784
Chris Lattnerd3e28342007-04-27 17:44:50 +00007785 // If we are casting a malloc or alloca to a pointer to a type of the same
7786 // size, rewrite the allocation instruction to allocate the "right" type.
7787 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7788 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7789 return V;
7790
Chris Lattnerd717c182007-05-05 22:32:24 +00007791 // If the source and destination are pointers, and this cast is equivalent
7792 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007793 // This can enhance SROA and other transforms that want type-safe pointers.
7794 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7795 unsigned NumZeros = 0;
7796 while (SrcElTy != DstElTy &&
7797 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7798 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7799 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7800 ++NumZeros;
7801 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007802
Chris Lattnerd3e28342007-04-27 17:44:50 +00007803 // If we found a path from the src to dest, create the getelementptr now.
7804 if (SrcElTy == DstElTy) {
7805 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007806 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7807 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007808 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007809 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007810
Reid Spencer3da59db2006-11-27 01:05:10 +00007811 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7812 if (SVI->hasOneUse()) {
7813 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7814 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007815 if (isa<VectorType>(DestTy) &&
7816 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007817 SVI->getType()->getNumElements()) {
7818 CastInst *Tmp;
7819 // If either of the operands is a cast from CI.getType(), then
7820 // evaluating the shuffle in the casted destination's type will allow
7821 // us to eliminate at least one cast.
7822 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7823 Tmp->getOperand(0)->getType() == DestTy) ||
7824 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7825 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007826 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7827 SVI->getOperand(0), DestTy, &CI);
7828 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7829 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007830 // Return a new shuffle vector. Use the same element ID's, as we
7831 // know the vector types match #elts.
7832 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007833 }
7834 }
7835 }
7836 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007837 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007838}
7839
Chris Lattnere576b912004-04-09 23:46:01 +00007840/// GetSelectFoldableOperands - We want to turn code that looks like this:
7841/// %C = or %A, %B
7842/// %D = select %cond, %C, %A
7843/// into:
7844/// %C = select %cond, %B, 0
7845/// %D = or %A, %C
7846///
7847/// Assuming that the specified instruction is an operand to the select, return
7848/// a bitmask indicating which operands of this instruction are foldable if they
7849/// equal the other incoming value of the select.
7850///
7851static unsigned GetSelectFoldableOperands(Instruction *I) {
7852 switch (I->getOpcode()) {
7853 case Instruction::Add:
7854 case Instruction::Mul:
7855 case Instruction::And:
7856 case Instruction::Or:
7857 case Instruction::Xor:
7858 return 3; // Can fold through either operand.
7859 case Instruction::Sub: // Can only fold on the amount subtracted.
7860 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007861 case Instruction::LShr:
7862 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007863 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007864 default:
7865 return 0; // Cannot fold
7866 }
7867}
7868
7869/// GetSelectFoldableConstant - For the same transformation as the previous
7870/// function, return the identity constant that goes into the select.
7871static Constant *GetSelectFoldableConstant(Instruction *I) {
7872 switch (I->getOpcode()) {
7873 default: assert(0 && "This cannot happen!"); abort();
7874 case Instruction::Add:
7875 case Instruction::Sub:
7876 case Instruction::Or:
7877 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007878 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007879 case Instruction::LShr:
7880 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007881 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007882 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007883 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007884 case Instruction::Mul:
7885 return ConstantInt::get(I->getType(), 1);
7886 }
7887}
7888
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007889/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7890/// have the same opcode and only one use each. Try to simplify this.
7891Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7892 Instruction *FI) {
7893 if (TI->getNumOperands() == 1) {
7894 // If this is a non-volatile load or a cast from the same type,
7895 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007896 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007897 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7898 return 0;
7899 } else {
7900 return 0; // unknown unary op.
7901 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007902
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007903 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00007904 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7905 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007906 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007907 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00007908 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007909 }
7910
Reid Spencer832254e2007-02-02 02:16:23 +00007911 // Only handle binary operators here.
7912 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007913 return 0;
7914
7915 // Figure out if the operations have any operands in common.
7916 Value *MatchOp, *OtherOpT, *OtherOpF;
7917 bool MatchIsOpZero;
7918 if (TI->getOperand(0) == FI->getOperand(0)) {
7919 MatchOp = TI->getOperand(0);
7920 OtherOpT = TI->getOperand(1);
7921 OtherOpF = FI->getOperand(1);
7922 MatchIsOpZero = true;
7923 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7924 MatchOp = TI->getOperand(1);
7925 OtherOpT = TI->getOperand(0);
7926 OtherOpF = FI->getOperand(0);
7927 MatchIsOpZero = false;
7928 } else if (!TI->isCommutative()) {
7929 return 0;
7930 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7931 MatchOp = TI->getOperand(0);
7932 OtherOpT = TI->getOperand(1);
7933 OtherOpF = FI->getOperand(0);
7934 MatchIsOpZero = true;
7935 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7936 MatchOp = TI->getOperand(1);
7937 OtherOpT = TI->getOperand(0);
7938 OtherOpF = FI->getOperand(1);
7939 MatchIsOpZero = true;
7940 } else {
7941 return 0;
7942 }
7943
7944 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00007945 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
7946 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007947 InsertNewInstBefore(NewSI, SI);
7948
7949 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7950 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007951 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007952 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007953 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007954 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007955 assert(0 && "Shouldn't get here");
7956 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007957}
7958
Chris Lattner3d69f462004-03-12 05:52:32 +00007959Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007960 Value *CondVal = SI.getCondition();
7961 Value *TrueVal = SI.getTrueValue();
7962 Value *FalseVal = SI.getFalseValue();
7963
7964 // select true, X, Y -> X
7965 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007966 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007967 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007968
7969 // select C, X, X -> X
7970 if (TrueVal == FalseVal)
7971 return ReplaceInstUsesWith(SI, TrueVal);
7972
Chris Lattnere87597f2004-10-16 18:11:37 +00007973 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7974 return ReplaceInstUsesWith(SI, FalseVal);
7975 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7976 return ReplaceInstUsesWith(SI, TrueVal);
7977 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7978 if (isa<Constant>(TrueVal))
7979 return ReplaceInstUsesWith(SI, TrueVal);
7980 else
7981 return ReplaceInstUsesWith(SI, FalseVal);
7982 }
7983
Reid Spencer4fe16d62007-01-11 18:21:29 +00007984 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007985 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007986 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007987 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007988 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007989 } else {
7990 // Change: A = select B, false, C --> A = and !B, C
7991 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007992 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00007993 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007994 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007995 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007996 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007997 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007998 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007999 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008000 } else {
8001 // Change: A = select B, C, true --> A = or !B, C
8002 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008003 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008004 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008005 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008006 }
8007 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008008
8009 // select a, b, a -> a&b
8010 // select a, a, b -> a|b
8011 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008012 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008013 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008014 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008015 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008016
Chris Lattner2eefe512004-04-09 19:05:30 +00008017 // Selecting between two integer constants?
8018 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8019 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008020 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008021 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008022 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008023 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008024 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008025 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008026 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008027 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008028 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008029 }
Chris Lattnerba417832007-04-11 06:12:58 +00008030
8031 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008032
Reid Spencere4d87aa2006-12-23 06:05:41 +00008033 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008034
Reid Spencere4d87aa2006-12-23 06:05:41 +00008035 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008036 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008037 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008038 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008039 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008040 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008041 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008042 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008043 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008044 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008045 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008046 InsertNewInstBefore(SRA, SI);
8047
Reid Spencer3da59db2006-11-27 01:05:10 +00008048 // Finally, convert to the type of the select RHS. We figure out
8049 // if this requires a SExt, Trunc or BitCast based on the sizes.
8050 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008051 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8052 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008053 if (SRASize < SISize)
8054 opc = Instruction::SExt;
8055 else if (SRASize > SISize)
8056 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008057 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008058 }
8059 }
8060
8061
8062 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008063 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008064 // non-constant value, eliminate this whole mess. This corresponds to
8065 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008066 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008067 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008068 cast<Constant>(IC->getOperand(1))->isNullValue())
8069 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8070 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008071 isa<ConstantInt>(ICA->getOperand(1)) &&
8072 (ICA->getOperand(1) == TrueValC ||
8073 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008074 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8075 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008076 // know whether we have a icmp_ne or icmp_eq and whether the
8077 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008078 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008079 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008080 Value *V = ICA;
8081 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008082 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008083 Instruction::Xor, V, ICA->getOperand(1)), SI);
8084 return ReplaceInstUsesWith(SI, V);
8085 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008086 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008087 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008088
8089 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008090 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8091 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008092 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008093 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8094 // This is not safe in general for floating point:
8095 // consider X== -0, Y== +0.
8096 // It becomes safe if either operand is a nonzero constant.
8097 ConstantFP *CFPt, *CFPf;
8098 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8099 !CFPt->getValueAPF().isZero()) ||
8100 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8101 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008102 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008103 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008104 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008105 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008106 return ReplaceInstUsesWith(SI, TrueVal);
8107 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8108
Reid Spencere4d87aa2006-12-23 06:05:41 +00008109 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008110 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008111 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8112 // This is not safe in general for floating point:
8113 // consider X== -0, Y== +0.
8114 // It becomes safe if either operand is a nonzero constant.
8115 ConstantFP *CFPt, *CFPf;
8116 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8117 !CFPt->getValueAPF().isZero()) ||
8118 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8119 !CFPf->getValueAPF().isZero()))
8120 return ReplaceInstUsesWith(SI, FalseVal);
8121 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008122 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008123 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8124 return ReplaceInstUsesWith(SI, TrueVal);
8125 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8126 }
8127 }
8128
8129 // See if we are selecting two values based on a comparison of the two values.
8130 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8131 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8132 // Transform (X == Y) ? X : Y -> Y
8133 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8134 return ReplaceInstUsesWith(SI, FalseVal);
8135 // Transform (X != Y) ? X : Y -> X
8136 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8137 return ReplaceInstUsesWith(SI, TrueVal);
8138 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8139
8140 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8141 // Transform (X == Y) ? Y : X -> X
8142 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8143 return ReplaceInstUsesWith(SI, FalseVal);
8144 // Transform (X != Y) ? Y : X -> Y
8145 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008146 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008147 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8148 }
8149 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008150
Chris Lattner87875da2005-01-13 22:52:24 +00008151 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8152 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8153 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008154 Instruction *AddOp = 0, *SubOp = 0;
8155
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008156 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8157 if (TI->getOpcode() == FI->getOpcode())
8158 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8159 return IV;
8160
8161 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8162 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008163 if (TI->getOpcode() == Instruction::Sub &&
8164 FI->getOpcode() == Instruction::Add) {
8165 AddOp = FI; SubOp = TI;
8166 } else if (FI->getOpcode() == Instruction::Sub &&
8167 TI->getOpcode() == Instruction::Add) {
8168 AddOp = TI; SubOp = FI;
8169 }
8170
8171 if (AddOp) {
8172 Value *OtherAddOp = 0;
8173 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8174 OtherAddOp = AddOp->getOperand(1);
8175 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8176 OtherAddOp = AddOp->getOperand(0);
8177 }
8178
8179 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008180 // So at this point we know we have (Y -> OtherAddOp):
8181 // select C, (add X, Y), (sub X, Z)
8182 Value *NegVal; // Compute -Z
8183 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8184 NegVal = ConstantExpr::getNeg(C);
8185 } else {
8186 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008187 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008188 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008189
8190 Value *NewTrueOp = OtherAddOp;
8191 Value *NewFalseOp = NegVal;
8192 if (AddOp != TI)
8193 std::swap(NewTrueOp, NewFalseOp);
8194 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008195 SelectInst::Create(CondVal, NewTrueOp,
8196 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008197
8198 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008199 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008200 }
8201 }
8202 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008203
Chris Lattnere576b912004-04-09 23:46:01 +00008204 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008205 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008206 // See the comment above GetSelectFoldableOperands for a description of the
8207 // transformation we are doing here.
8208 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8209 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8210 !isa<Constant>(FalseVal))
8211 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8212 unsigned OpToFold = 0;
8213 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8214 OpToFold = 1;
8215 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8216 OpToFold = 2;
8217 }
8218
8219 if (OpToFold) {
8220 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008221 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008222 SelectInst::Create(SI.getCondition(),
8223 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008224 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008225 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008226 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008227 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008228 else {
8229 assert(0 && "Unknown instruction!!");
8230 }
8231 }
8232 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008233
Chris Lattnere576b912004-04-09 23:46:01 +00008234 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8235 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8236 !isa<Constant>(TrueVal))
8237 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8238 unsigned OpToFold = 0;
8239 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8240 OpToFold = 1;
8241 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8242 OpToFold = 2;
8243 }
8244
8245 if (OpToFold) {
8246 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008247 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008248 SelectInst::Create(SI.getCondition(), C,
8249 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008250 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008251 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008252 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008253 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008254 else
Chris Lattnere576b912004-04-09 23:46:01 +00008255 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008256 }
8257 }
8258 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008259
8260 if (BinaryOperator::isNot(CondVal)) {
8261 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8262 SI.setOperand(1, FalseVal);
8263 SI.setOperand(2, TrueVal);
8264 return &SI;
8265 }
8266
Chris Lattner3d69f462004-03-12 05:52:32 +00008267 return 0;
8268}
8269
Dan Gohmaneee962e2008-04-10 18:43:06 +00008270/// EnforceKnownAlignment - If the specified pointer points to an object that
8271/// we control, modify the object's alignment to PrefAlign. This isn't
8272/// often possible though. If alignment is important, a more reliable approach
8273/// is to simply align all global variables and allocation instructions to
8274/// their preferred alignment from the beginning.
8275///
8276static unsigned EnforceKnownAlignment(Value *V,
8277 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008278
Dan Gohmaneee962e2008-04-10 18:43:06 +00008279 User *U = dyn_cast<User>(V);
8280 if (!U) return Align;
8281
8282 switch (getOpcode(U)) {
8283 default: break;
8284 case Instruction::BitCast:
8285 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8286 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008287 // If all indexes are zero, it is just the alignment of the base pointer.
8288 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008289 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8290 if (!isa<Constant>(U->getOperand(i)) ||
8291 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008292 AllZeroOperands = false;
8293 break;
8294 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008295
8296 if (AllZeroOperands) {
8297 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008298 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008299 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008300 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008301 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008302 }
8303
8304 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8305 // If there is a large requested alignment and we can, bump up the alignment
8306 // of the global.
8307 if (!GV->isDeclaration()) {
8308 GV->setAlignment(PrefAlign);
8309 Align = PrefAlign;
8310 }
8311 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8312 // If there is a requested alignment and if this is an alloca, round up. We
8313 // don't do this for malloc, because some systems can't respect the request.
8314 if (isa<AllocaInst>(AI)) {
8315 AI->setAlignment(PrefAlign);
8316 Align = PrefAlign;
8317 }
8318 }
8319
8320 return Align;
8321}
8322
8323/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8324/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8325/// and it is more than the alignment of the ultimate object, see if we can
8326/// increase the alignment of the ultimate object, making this check succeed.
8327unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8328 unsigned PrefAlign) {
8329 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8330 sizeof(PrefAlign) * CHAR_BIT;
8331 APInt Mask = APInt::getAllOnesValue(BitWidth);
8332 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8333 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8334 unsigned TrailZ = KnownZero.countTrailingOnes();
8335 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8336
8337 if (PrefAlign > Align)
8338 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8339
8340 // We don't need to make any adjustment.
8341 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008342}
8343
Chris Lattnerf497b022008-01-13 23:50:23 +00008344Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008345 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8346 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008347 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8348 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8349
8350 if (CopyAlign < MinAlign) {
8351 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8352 return MI;
8353 }
8354
8355 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8356 // load/store.
8357 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8358 if (MemOpLength == 0) return 0;
8359
Chris Lattner37ac6082008-01-14 00:28:35 +00008360 // Source and destination pointer types are always "i8*" for intrinsic. See
8361 // if the size is something we can handle with a single primitive load/store.
8362 // A single load+store correctly handles overlapping memory in the memmove
8363 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008364 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008365 if (Size == 0) return MI; // Delete this mem transfer.
8366
8367 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008368 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008369
Chris Lattner37ac6082008-01-14 00:28:35 +00008370 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008371 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008372
8373 // Memcpy forces the use of i8* for the source and destination. That means
8374 // that if you're using memcpy to move one double around, you'll get a cast
8375 // from double* to i8*. We'd much rather use a double load+store rather than
8376 // an i64 load+store, here because this improves the odds that the source or
8377 // dest address will be promotable. See if we can find a better type than the
8378 // integer datatype.
8379 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8380 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8381 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8382 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8383 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00008384 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00008385 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8386 if (STy->getNumElements() == 1)
8387 SrcETy = STy->getElementType(0);
8388 else
8389 break;
8390 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8391 if (ATy->getNumElements() == 1)
8392 SrcETy = ATy->getElementType();
8393 else
8394 break;
8395 } else
8396 break;
8397 }
8398
Dan Gohman8f8e2692008-05-23 01:52:21 +00008399 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00008400 NewPtrTy = PointerType::getUnqual(SrcETy);
8401 }
8402 }
8403
8404
Chris Lattnerf497b022008-01-13 23:50:23 +00008405 // If the memcpy/memmove provides better alignment info than we can
8406 // infer, use it.
8407 SrcAlign = std::max(SrcAlign, CopyAlign);
8408 DstAlign = std::max(DstAlign, CopyAlign);
8409
8410 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8411 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008412 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8413 InsertNewInstBefore(L, *MI);
8414 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8415
8416 // Set the size of the copy to 0, it will be deleted on the next iteration.
8417 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8418 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008419}
Chris Lattner3d69f462004-03-12 05:52:32 +00008420
Chris Lattner69ea9d22008-04-30 06:39:11 +00008421Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8422 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8423 if (MI->getAlignment()->getZExtValue() < Alignment) {
8424 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8425 return MI;
8426 }
8427
8428 // Extract the length and alignment and fill if they are constant.
8429 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8430 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8431 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8432 return 0;
8433 uint64_t Len = LenC->getZExtValue();
8434 Alignment = MI->getAlignment()->getZExtValue();
8435
8436 // If the length is zero, this is a no-op
8437 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8438
8439 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8440 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8441 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8442
8443 Value *Dest = MI->getDest();
8444 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8445
8446 // Alignment 0 is identity for alignment 1 for memset, but not store.
8447 if (Alignment == 0) Alignment = 1;
8448
8449 // Extract the fill value and store.
8450 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8451 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8452 Alignment), *MI);
8453
8454 // Set the size of the copy to 0, it will be deleted on the next iteration.
8455 MI->setLength(Constant::getNullValue(LenC->getType()));
8456 return MI;
8457 }
8458
8459 return 0;
8460}
8461
8462
Chris Lattner8b0ea312006-01-13 20:11:04 +00008463/// visitCallInst - CallInst simplification. This mostly only handles folding
8464/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8465/// the heavy lifting.
8466///
Chris Lattner9fe38862003-06-19 17:00:31 +00008467Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008468 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8469 if (!II) return visitCallSite(&CI);
8470
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008471 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8472 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008473 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008474 bool Changed = false;
8475
8476 // memmove/cpy/set of zero bytes is a noop.
8477 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8478 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8479
Chris Lattner35b9e482004-10-12 04:52:52 +00008480 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008481 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008482 // Replace the instruction with just byte operations. We would
8483 // transform other cases to loads/stores, but we don't know if
8484 // alignment is sufficient.
8485 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008486 }
8487
Chris Lattner35b9e482004-10-12 04:52:52 +00008488 // If we have a memmove and the source operation is a constant global,
8489 // then the source and dest pointers can't alias, so we can change this
8490 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008491 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008492 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8493 if (GVSrc->isConstant()) {
8494 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008495 Intrinsic::ID MemCpyID;
8496 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8497 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008498 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008499 MemCpyID = Intrinsic::memcpy_i64;
8500 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008501 Changed = true;
8502 }
Chris Lattnera935db82008-05-28 05:30:41 +00008503
8504 // memmove(x,x,size) -> noop.
8505 if (MMI->getSource() == MMI->getDest())
8506 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00008507 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008508
Chris Lattner95a959d2006-03-06 20:18:44 +00008509 // If we can determine a pointer alignment that is bigger than currently
8510 // set, update the alignment.
8511 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008512 if (Instruction *I = SimplifyMemTransfer(MI))
8513 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008514 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8515 if (Instruction *I = SimplifyMemSet(MSI))
8516 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008517 }
8518
Chris Lattner8b0ea312006-01-13 20:11:04 +00008519 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008520 } else {
8521 switch (II->getIntrinsicID()) {
8522 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008523 case Intrinsic::ppc_altivec_lvx:
8524 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008525 case Intrinsic::x86_sse_loadu_ps:
8526 case Intrinsic::x86_sse2_loadu_pd:
8527 case Intrinsic::x86_sse2_loadu_dq:
8528 // Turn PPC lvx -> load if the pointer is known aligned.
8529 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008530 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008531 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8532 PointerType::getUnqual(II->getType()),
8533 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008534 return new LoadInst(Ptr);
8535 }
8536 break;
8537 case Intrinsic::ppc_altivec_stvx:
8538 case Intrinsic::ppc_altivec_stvxl:
8539 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008540 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008541 const Type *OpPtrTy =
8542 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008543 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008544 return new StoreInst(II->getOperand(1), Ptr);
8545 }
8546 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008547 case Intrinsic::x86_sse_storeu_ps:
8548 case Intrinsic::x86_sse2_storeu_pd:
8549 case Intrinsic::x86_sse2_storeu_dq:
8550 case Intrinsic::x86_sse2_storel_dq:
8551 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008552 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008553 const Type *OpPtrTy =
8554 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008555 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008556 return new StoreInst(II->getOperand(2), Ptr);
8557 }
8558 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008559
8560 case Intrinsic::x86_sse_cvttss2si: {
8561 // These intrinsics only demands the 0th element of its input vector. If
8562 // we can simplify the input based on that, do so now.
8563 uint64_t UndefElts;
8564 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8565 UndefElts)) {
8566 II->setOperand(1, V);
8567 return II;
8568 }
8569 break;
8570 }
8571
Chris Lattnere2ed0572006-04-06 19:19:17 +00008572 case Intrinsic::ppc_altivec_vperm:
8573 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008574 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008575 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8576
8577 // Check that all of the elements are integer constants or undefs.
8578 bool AllEltsOk = true;
8579 for (unsigned i = 0; i != 16; ++i) {
8580 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8581 !isa<UndefValue>(Mask->getOperand(i))) {
8582 AllEltsOk = false;
8583 break;
8584 }
8585 }
8586
8587 if (AllEltsOk) {
8588 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008589 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8590 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008591 Value *Result = UndefValue::get(Op0->getType());
8592
8593 // Only extract each element once.
8594 Value *ExtractedElts[32];
8595 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8596
8597 for (unsigned i = 0; i != 16; ++i) {
8598 if (isa<UndefValue>(Mask->getOperand(i)))
8599 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008600 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008601 Idx &= 31; // Match the hardware behavior.
8602
8603 if (ExtractedElts[Idx] == 0) {
8604 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008605 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008606 InsertNewInstBefore(Elt, CI);
8607 ExtractedElts[Idx] = Elt;
8608 }
8609
8610 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008611 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8612 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008613 InsertNewInstBefore(cast<Instruction>(Result), CI);
8614 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008615 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008616 }
8617 }
8618 break;
8619
Chris Lattnera728ddc2006-01-13 21:28:09 +00008620 case Intrinsic::stackrestore: {
8621 // If the save is right next to the restore, remove the restore. This can
8622 // happen when variable allocas are DCE'd.
8623 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8624 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8625 BasicBlock::iterator BI = SS;
8626 if (&*++BI == II)
8627 return EraseInstFromFunction(CI);
8628 }
8629 }
8630
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008631 // Scan down this block to see if there is another stack restore in the
8632 // same block without an intervening call/alloca.
8633 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008634 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008635 bool CannotRemove = false;
8636 for (++BI; &*BI != TI; ++BI) {
8637 if (isa<AllocaInst>(BI)) {
8638 CannotRemove = true;
8639 break;
8640 }
8641 if (isa<CallInst>(BI)) {
8642 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008643 CannotRemove = true;
8644 break;
8645 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008646 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008647 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008648 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008649 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008650
8651 // If the stack restore is in a return/unwind block and if there are no
8652 // allocas or calls between the restore and the return, nuke the restore.
8653 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8654 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008655 break;
8656 }
8657 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008658 }
8659
Chris Lattner8b0ea312006-01-13 20:11:04 +00008660 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008661}
8662
8663// InvokeInst simplification
8664//
8665Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008666 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008667}
8668
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008669/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8670/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008671static bool isSafeToEliminateVarargsCast(const CallSite CS,
8672 const CastInst * const CI,
8673 const TargetData * const TD,
8674 const int ix) {
8675 if (!CI->isLosslessCast())
8676 return false;
8677
8678 // The size of ByVal arguments is derived from the type, so we
8679 // can't change to a type with a different size. If the size were
8680 // passed explicitly we could avoid this check.
8681 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8682 return true;
8683
8684 const Type* SrcTy =
8685 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8686 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8687 if (!SrcTy->isSized() || !DstTy->isSized())
8688 return false;
8689 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8690 return false;
8691 return true;
8692}
8693
Chris Lattnera44d8a22003-10-07 22:32:43 +00008694// visitCallSite - Improvements for call and invoke instructions.
8695//
8696Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008697 bool Changed = false;
8698
8699 // If the callee is a constexpr cast of a function, attempt to move the cast
8700 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008701 if (transformConstExprCastCall(CS)) return 0;
8702
Chris Lattner6c266db2003-10-07 22:54:13 +00008703 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008704
Chris Lattner08b22ec2005-05-13 07:09:09 +00008705 if (Function *CalleeF = dyn_cast<Function>(Callee))
8706 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8707 Instruction *OldCall = CS.getInstruction();
8708 // If the call and callee calling conventions don't match, this call must
8709 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008710 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008711 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8712 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008713 if (!OldCall->use_empty())
8714 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8715 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8716 return EraseInstFromFunction(*OldCall);
8717 return 0;
8718 }
8719
Chris Lattner17be6352004-10-18 02:59:09 +00008720 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8721 // This instruction is not reachable, just remove it. We insert a store to
8722 // undef so that we know that this code is not reachable, despite the fact
8723 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008724 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008725 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008726 CS.getInstruction());
8727
8728 if (!CS.getInstruction()->use_empty())
8729 CS.getInstruction()->
8730 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8731
8732 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8733 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008734 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8735 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008736 }
Chris Lattner17be6352004-10-18 02:59:09 +00008737 return EraseInstFromFunction(*CS.getInstruction());
8738 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008739
Duncan Sandscdb6d922007-09-17 10:26:40 +00008740 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8741 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8742 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8743 return transformCallThroughTrampoline(CS);
8744
Chris Lattner6c266db2003-10-07 22:54:13 +00008745 const PointerType *PTy = cast<PointerType>(Callee->getType());
8746 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8747 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00008748 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00008749 // See if we can optimize any arguments passed through the varargs area of
8750 // the call.
8751 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00008752 E = CS.arg_end(); I != E; ++I, ++ix) {
8753 CastInst *CI = dyn_cast<CastInst>(*I);
8754 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8755 *I = CI->getOperand(0);
8756 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00008757 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00008758 }
Chris Lattner6c266db2003-10-07 22:54:13 +00008759 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008760
Duncan Sandsf0c33542007-12-19 21:13:37 +00008761 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008762 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008763 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008764 Changed = true;
8765 }
8766
Chris Lattner6c266db2003-10-07 22:54:13 +00008767 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008768}
8769
Chris Lattner9fe38862003-06-19 17:00:31 +00008770// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8771// attempt to move the cast to the arguments of the call/invoke.
8772//
8773bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8774 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8775 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008776 if (CE->getOpcode() != Instruction::BitCast ||
8777 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008778 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008779 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008780 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008781 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008782
8783 // Okay, this is a cast from a function to a different type. Unless doing so
8784 // would cause a type conversion of one of our arguments, change this call to
8785 // be a direct call with arguments casted to the appropriate types.
8786 //
8787 const FunctionType *FT = Callee->getFunctionType();
8788 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008789 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00008790
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008791 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00008792 return false; // TODO: Handle multiple return values.
8793
Chris Lattnerf78616b2004-01-14 06:06:08 +00008794 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008795 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00008796 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008797 // Conversion is ok if changing from one pointer type to another or from
8798 // a pointer to an integer of the same size.
8799 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8800 isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType()))
Chris Lattnerec479922007-01-06 02:09:32 +00008801 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008802
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008803 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008804 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008805 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008806 return false; // Cannot transform this return value.
8807
Chris Lattner58d74912008-03-12 17:45:29 +00008808 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8809 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008810 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00008811 return false; // Attribute not compatible with transformed value.
8812 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008813
Chris Lattnerf78616b2004-01-14 06:06:08 +00008814 // If the callsite is an invoke instruction, and the return value is used by
8815 // a PHI node in a successor, we cannot change the return type of the call
8816 // because there is no place to put the cast instruction (without breaking
8817 // the critical edge). Bail out in this case.
8818 if (!Caller->use_empty())
8819 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8820 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8821 UI != E; ++UI)
8822 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8823 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008824 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008825 return false;
8826 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008827
8828 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8829 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008830
Chris Lattner9fe38862003-06-19 17:00:31 +00008831 CallSite::arg_iterator AI = CS.arg_begin();
8832 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8833 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008834 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008835
8836 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008837 return false; // Cannot transform this parameter value.
8838
Chris Lattner58d74912008-03-12 17:45:29 +00008839 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8840 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008841
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008842 // Converting from one pointer type to another or between a pointer and an
8843 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00008844 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008845 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8846 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00008847 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008848 }
8849
8850 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008851 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008852 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008853
Chris Lattner58d74912008-03-12 17:45:29 +00008854 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8855 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008856 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008857 // won't be dropping them. Check that these extra arguments have attributes
8858 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008859 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8860 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008861 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008862 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008863 if (PAttrs & ParamAttr::VarArgsIncompatible)
8864 return false;
8865 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008866
Chris Lattner9fe38862003-06-19 17:00:31 +00008867 // Okay, we decided that this is a safe thing to do: go ahead and start
8868 // inserting cast instructions as necessary...
8869 std::vector<Value*> Args;
8870 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008871 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008872 attrVec.reserve(NumCommonArgs);
8873
8874 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008875 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008876
8877 // If the return value is not being used, the type may not be compatible
8878 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008879 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008880
8881 // Add the new return attributes.
8882 if (RAttrs)
8883 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008884
8885 AI = CS.arg_begin();
8886 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8887 const Type *ParamTy = FT->getParamType(i);
8888 if ((*AI)->getType() == ParamTy) {
8889 Args.push_back(*AI);
8890 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008891 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008892 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008893 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008894 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008895 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008896
8897 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008898 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008899 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008900 }
8901
8902 // If the function takes more arguments than the call was taking, add them
8903 // now...
8904 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8905 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8906
8907 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008908 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008909 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008910 cerr << "WARNING: While resolving call to function '"
8911 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008912 } else {
8913 // Add all of the arguments in their promoted form to the arg list...
8914 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8915 const Type *PTy = getPromotedType((*AI)->getType());
8916 if (PTy != (*AI)->getType()) {
8917 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008918 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8919 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008920 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008921 InsertNewInstBefore(Cast, *Caller);
8922 Args.push_back(Cast);
8923 } else {
8924 Args.push_back(*AI);
8925 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008926
Duncan Sandse1e520f2008-01-13 08:02:44 +00008927 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008928 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00008929 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8930 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008931 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008932 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008933
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008934 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008935 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008936
Chris Lattner58d74912008-03-12 17:45:29 +00008937 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008938
Chris Lattner9fe38862003-06-19 17:00:31 +00008939 Instruction *NC;
8940 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00008941 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008942 Args.begin(), Args.end(),
8943 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008944 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008945 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008946 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00008947 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
8948 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008949 CallInst *CI = cast<CallInst>(Caller);
8950 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008951 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008952 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008953 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008954 }
8955
Chris Lattner6934a042007-02-11 01:23:03 +00008956 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008957 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008958 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008959 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008960 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008961 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008962 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008963
8964 // If this is an invoke instruction, we should insert it after the first
8965 // non-phi, instruction in the normal successor block.
8966 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00008967 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00008968 InsertNewInstBefore(NC, *I);
8969 } else {
8970 // Otherwise, it's a call, just insert cast right after the call instr
8971 InsertNewInstBefore(NC, *Caller);
8972 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008973 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008974 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008975 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008976 }
8977 }
8978
8979 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8980 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008981 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008982 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008983 return true;
8984}
8985
Duncan Sandscdb6d922007-09-17 10:26:40 +00008986// transformCallThroughTrampoline - Turn a call to a function created by the
8987// init_trampoline intrinsic into a direct call to the underlying function.
8988//
8989Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8990 Value *Callee = CS.getCalledValue();
8991 const PointerType *PTy = cast<PointerType>(Callee->getType());
8992 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00008993 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008994
8995 // If the call already has the 'nest' attribute somewhere then give up -
8996 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00008997 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008998 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008999
9000 IntrinsicInst *Tramp =
9001 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9002
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009003 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009004 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9005 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9006
Chris Lattner58d74912008-03-12 17:45:29 +00009007 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9008 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009009 unsigned NestIdx = 1;
9010 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009011 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009012
9013 // Look for a parameter marked with the 'nest' attribute.
9014 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9015 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009016 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009017 // Record the parameter type and any other attributes.
9018 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009019 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009020 break;
9021 }
9022
9023 if (NestTy) {
9024 Instruction *Caller = CS.getInstruction();
9025 std::vector<Value*> NewArgs;
9026 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9027
Chris Lattner58d74912008-03-12 17:45:29 +00009028 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9029 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009030
Duncan Sandscdb6d922007-09-17 10:26:40 +00009031 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009032 // mean appending it. Likewise for attributes.
9033
9034 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009035 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9036 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009037
Duncan Sandscdb6d922007-09-17 10:26:40 +00009038 {
9039 unsigned Idx = 1;
9040 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9041 do {
9042 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009043 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009044 Value *NestVal = Tramp->getOperand(3);
9045 if (NestVal->getType() != NestTy)
9046 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9047 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009048 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009049 }
9050
9051 if (I == E)
9052 break;
9053
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009054 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009055 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009056 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009057 NewAttrs.push_back
9058 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009059
9060 ++Idx, ++I;
9061 } while (1);
9062 }
9063
9064 // The trampoline may have been bitcast to a bogus type (FTy).
9065 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009066 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009067
Duncan Sandscdb6d922007-09-17 10:26:40 +00009068 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009069 NewTypes.reserve(FTy->getNumParams()+1);
9070
Duncan Sandscdb6d922007-09-17 10:26:40 +00009071 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009072 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009073 {
9074 unsigned Idx = 1;
9075 FunctionType::param_iterator I = FTy->param_begin(),
9076 E = FTy->param_end();
9077
9078 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009079 if (Idx == NestIdx)
9080 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009081 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009082
9083 if (I == E)
9084 break;
9085
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009086 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009087 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009088
9089 ++Idx, ++I;
9090 } while (1);
9091 }
9092
9093 // Replace the trampoline call with a direct call. Let the generic
9094 // code sort out any function type mismatches.
9095 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009096 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009097 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9098 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009099 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009100
9101 Instruction *NewCaller;
9102 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009103 NewCaller = InvokeInst::Create(NewCallee,
9104 II->getNormalDest(), II->getUnwindDest(),
9105 NewArgs.begin(), NewArgs.end(),
9106 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009107 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009108 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009109 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009110 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9111 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009112 if (cast<CallInst>(Caller)->isTailCall())
9113 cast<CallInst>(NewCaller)->setTailCall();
9114 cast<CallInst>(NewCaller)->
9115 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009116 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009117 }
9118 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9119 Caller->replaceAllUsesWith(NewCaller);
9120 Caller->eraseFromParent();
9121 RemoveFromWorkList(Caller);
9122 return 0;
9123 }
9124 }
9125
9126 // Replace the trampoline call with a direct call. Since there is no 'nest'
9127 // parameter, there is no need to adjust the argument list. Let the generic
9128 // code sort out any function type mismatches.
9129 Constant *NewCallee =
9130 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9131 CS.setCalledFunction(NewCallee);
9132 return CS.getInstruction();
9133}
9134
Chris Lattner7da52b22006-11-01 04:51:18 +00009135/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9136/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9137/// and a single binop.
9138Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9139 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009140 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9141 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009142 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009143 Value *LHSVal = FirstInst->getOperand(0);
9144 Value *RHSVal = FirstInst->getOperand(1);
9145
9146 const Type *LHSType = LHSVal->getType();
9147 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009148
9149 // Scan to see if all operands are the same opcode, all have one use, and all
9150 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009151 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009152 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009153 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009154 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009155 // types or GEP's with different index types.
9156 I->getOperand(0)->getType() != LHSType ||
9157 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009158 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009159
9160 // If they are CmpInst instructions, check their predicates
9161 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9162 if (cast<CmpInst>(I)->getPredicate() !=
9163 cast<CmpInst>(FirstInst)->getPredicate())
9164 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009165
9166 // Keep track of which operand needs a phi node.
9167 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9168 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009169 }
9170
Chris Lattner53738a42006-11-08 19:42:28 +00009171 // Otherwise, this is safe to transform, determine if it is profitable.
9172
9173 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9174 // Indexes are often folded into load/store instructions, so we don't want to
9175 // hide them behind a phi.
9176 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9177 return 0;
9178
Chris Lattner7da52b22006-11-01 04:51:18 +00009179 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009180 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009181 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009182 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009183 NewLHS = PHINode::Create(LHSType,
9184 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009185 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9186 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009187 InsertNewInstBefore(NewLHS, PN);
9188 LHSVal = NewLHS;
9189 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009190
9191 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009192 NewRHS = PHINode::Create(RHSType,
9193 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009194 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9195 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009196 InsertNewInstBefore(NewRHS, PN);
9197 RHSVal = NewRHS;
9198 }
9199
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009200 // Add all operands to the new PHIs.
9201 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9202 if (NewLHS) {
9203 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9204 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9205 }
9206 if (NewRHS) {
9207 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9208 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9209 }
9210 }
9211
Chris Lattner7da52b22006-11-01 04:51:18 +00009212 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009213 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009214 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009215 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009216 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009217 else {
9218 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009219 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009220 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009221}
9222
Chris Lattner76c73142006-11-01 07:13:54 +00009223/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9224/// of the block that defines it. This means that it must be obvious the value
9225/// of the load is not changed from the point of the load to the end of the
9226/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009227///
9228/// Finally, it is safe, but not profitable, to sink a load targetting a
9229/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9230/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009231static bool isSafeToSinkLoad(LoadInst *L) {
9232 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9233
9234 for (++BBI; BBI != E; ++BBI)
9235 if (BBI->mayWriteToMemory())
9236 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009237
9238 // Check for non-address taken alloca. If not address-taken already, it isn't
9239 // profitable to do this xform.
9240 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9241 bool isAddressTaken = false;
9242 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9243 UI != E; ++UI) {
9244 if (isa<LoadInst>(UI)) continue;
9245 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9246 // If storing TO the alloca, then the address isn't taken.
9247 if (SI->getOperand(1) == AI) continue;
9248 }
9249 isAddressTaken = true;
9250 break;
9251 }
9252
9253 if (!isAddressTaken)
9254 return false;
9255 }
9256
Chris Lattner76c73142006-11-01 07:13:54 +00009257 return true;
9258}
9259
Chris Lattner9fe38862003-06-19 17:00:31 +00009260
Chris Lattnerbac32862004-11-14 19:13:23 +00009261// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9262// operator and they all are only used by the PHI, PHI together their
9263// inputs, and do the operation once, to the result of the PHI.
9264Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9265 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9266
9267 // Scan the instruction, looking for input operations that can be folded away.
9268 // If all input operands to the phi are the same instruction (e.g. a cast from
9269 // the same type or "+42") we can pull the operation through the PHI, reducing
9270 // code size and simplifying code.
9271 Constant *ConstantOp = 0;
9272 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009273 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009274 if (isa<CastInst>(FirstInst)) {
9275 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009276 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009277 // Can fold binop, compare or shift here if the RHS is a constant,
9278 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009279 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009280 if (ConstantOp == 0)
9281 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009282 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9283 isVolatile = LI->isVolatile();
9284 // We can't sink the load if the loaded value could be modified between the
9285 // load and the PHI.
9286 if (LI->getParent() != PN.getIncomingBlock(0) ||
9287 !isSafeToSinkLoad(LI))
9288 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009289 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009290 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009291 return FoldPHIArgBinOpIntoPHI(PN);
9292 // Can't handle general GEPs yet.
9293 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009294 } else {
9295 return 0; // Cannot fold this operation.
9296 }
9297
9298 // Check to see if all arguments are the same operation.
9299 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9300 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9301 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009302 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009303 return 0;
9304 if (CastSrcTy) {
9305 if (I->getOperand(0)->getType() != CastSrcTy)
9306 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009307 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009308 // We can't sink the load if the loaded value could be modified between
9309 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009310 if (LI->isVolatile() != isVolatile ||
9311 LI->getParent() != PN.getIncomingBlock(i) ||
9312 !isSafeToSinkLoad(LI))
9313 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009314
9315 // If the PHI is volatile and its block has multiple successors, sinking
9316 // it would remove a load of the volatile value from the path through the
9317 // other successor.
9318 if (isVolatile &&
9319 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9320 return 0;
9321
9322
Chris Lattnerbac32862004-11-14 19:13:23 +00009323 } else if (I->getOperand(1) != ConstantOp) {
9324 return 0;
9325 }
9326 }
9327
9328 // Okay, they are all the same operation. Create a new PHI node of the
9329 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009330 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9331 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009332 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009333
9334 Value *InVal = FirstInst->getOperand(0);
9335 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009336
9337 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009338 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9339 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9340 if (NewInVal != InVal)
9341 InVal = 0;
9342 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9343 }
9344
9345 Value *PhiVal;
9346 if (InVal) {
9347 // The new PHI unions all of the same values together. This is really
9348 // common, so we handle it intelligently here for compile-time speed.
9349 PhiVal = InVal;
9350 delete NewPN;
9351 } else {
9352 InsertNewInstBefore(NewPN, PN);
9353 PhiVal = NewPN;
9354 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009355
Chris Lattnerbac32862004-11-14 19:13:23 +00009356 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009357 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009358 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009359 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009360 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009361 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009362 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009363 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009364 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9365
9366 // If this was a volatile load that we are merging, make sure to loop through
9367 // and mark all the input loads as non-volatile. If we don't do this, we will
9368 // insert a new volatile load and the old ones will not be deletable.
9369 if (isVolatile)
9370 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9371 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9372
9373 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009374}
Chris Lattnera1be5662002-05-02 17:06:02 +00009375
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009376/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9377/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009378static bool DeadPHICycle(PHINode *PN,
9379 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009380 if (PN->use_empty()) return true;
9381 if (!PN->hasOneUse()) return false;
9382
9383 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009384 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009385 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009386
9387 // Don't scan crazily complex things.
9388 if (PotentiallyDeadPHIs.size() == 16)
9389 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009390
9391 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9392 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009393
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009394 return false;
9395}
9396
Chris Lattnercf5008a2007-11-06 21:52:06 +00009397/// PHIsEqualValue - Return true if this phi node is always equal to
9398/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9399/// z = some value; x = phi (y, z); y = phi (x, z)
9400static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9401 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9402 // See if we already saw this PHI node.
9403 if (!ValueEqualPHIs.insert(PN))
9404 return true;
9405
9406 // Don't scan crazily complex things.
9407 if (ValueEqualPHIs.size() == 16)
9408 return false;
9409
9410 // Scan the operands to see if they are either phi nodes or are equal to
9411 // the value.
9412 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9413 Value *Op = PN->getIncomingValue(i);
9414 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9415 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9416 return false;
9417 } else if (Op != NonPhiInVal)
9418 return false;
9419 }
9420
9421 return true;
9422}
9423
9424
Chris Lattner473945d2002-05-06 18:06:38 +00009425// PHINode simplification
9426//
Chris Lattner7e708292002-06-25 16:13:24 +00009427Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009428 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009429 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009430
Owen Anderson7e057142006-07-10 22:03:18 +00009431 if (Value *V = PN.hasConstantValue())
9432 return ReplaceInstUsesWith(PN, V);
9433
Owen Anderson7e057142006-07-10 22:03:18 +00009434 // If all PHI operands are the same operation, pull them through the PHI,
9435 // reducing code size.
9436 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9437 PN.getIncomingValue(0)->hasOneUse())
9438 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9439 return Result;
9440
9441 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9442 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9443 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009444 if (PN.hasOneUse()) {
9445 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9446 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009447 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009448 PotentiallyDeadPHIs.insert(&PN);
9449 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9450 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9451 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009452
9453 // If this phi has a single use, and if that use just computes a value for
9454 // the next iteration of a loop, delete the phi. This occurs with unused
9455 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9456 // common case here is good because the only other things that catch this
9457 // are induction variable analysis (sometimes) and ADCE, which is only run
9458 // late.
9459 if (PHIUser->hasOneUse() &&
9460 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9461 PHIUser->use_back() == &PN) {
9462 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9463 }
9464 }
Owen Anderson7e057142006-07-10 22:03:18 +00009465
Chris Lattnercf5008a2007-11-06 21:52:06 +00009466 // We sometimes end up with phi cycles that non-obviously end up being the
9467 // same value, for example:
9468 // z = some value; x = phi (y, z); y = phi (x, z)
9469 // where the phi nodes don't necessarily need to be in the same block. Do a
9470 // quick check to see if the PHI node only contains a single non-phi value, if
9471 // so, scan to see if the phi cycle is actually equal to that value.
9472 {
9473 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9474 // Scan for the first non-phi operand.
9475 while (InValNo != NumOperandVals &&
9476 isa<PHINode>(PN.getIncomingValue(InValNo)))
9477 ++InValNo;
9478
9479 if (InValNo != NumOperandVals) {
9480 Value *NonPhiInVal = PN.getOperand(InValNo);
9481
9482 // Scan the rest of the operands to see if there are any conflicts, if so
9483 // there is no need to recursively scan other phis.
9484 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9485 Value *OpVal = PN.getIncomingValue(InValNo);
9486 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9487 break;
9488 }
9489
9490 // If we scanned over all operands, then we have one unique value plus
9491 // phi values. Scan PHI nodes to see if they all merge in each other or
9492 // the value.
9493 if (InValNo == NumOperandVals) {
9494 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9495 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9496 return ReplaceInstUsesWith(PN, NonPhiInVal);
9497 }
9498 }
9499 }
Chris Lattner60921c92003-12-19 05:58:40 +00009500 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009501}
9502
Reid Spencer17212df2006-12-12 09:18:51 +00009503static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9504 Instruction *InsertPoint,
9505 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009506 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9507 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009508 // We must cast correctly to the pointer type. Ensure that we
9509 // sign extend the integer value if it is smaller as this is
9510 // used for address computation.
9511 Instruction::CastOps opcode =
9512 (VTySize < PtrSize ? Instruction::SExt :
9513 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9514 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009515}
9516
Chris Lattnera1be5662002-05-02 17:06:02 +00009517
Chris Lattner7e708292002-06-25 16:13:24 +00009518Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009519 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009520 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009521 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009522 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009523 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009524
Chris Lattnere87597f2004-10-16 18:11:37 +00009525 if (isa<UndefValue>(GEP.getOperand(0)))
9526 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9527
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009528 bool HasZeroPointerIndex = false;
9529 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9530 HasZeroPointerIndex = C->isNullValue();
9531
9532 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009533 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009534
Chris Lattner28977af2004-04-05 01:30:19 +00009535 // Eliminate unneeded casts for indices.
9536 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009537
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009538 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009539 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009540 if (isa<SequentialType>(*GTI)) {
9541 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009542 if (CI->getOpcode() == Instruction::ZExt ||
9543 CI->getOpcode() == Instruction::SExt) {
9544 const Type *SrcTy = CI->getOperand(0)->getType();
9545 // We can eliminate a cast from i32 to i64 iff the target
9546 // is a 32-bit pointer target.
9547 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9548 MadeChange = true;
9549 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009550 }
9551 }
9552 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009553 // If we are using a wider index than needed for this platform, shrink it
9554 // to what we need. If the incoming value needs a cast instruction,
9555 // insert it. This explicit cast can make subsequent optimizations more
9556 // obvious.
9557 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009558 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009559 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009560 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009561 MadeChange = true;
9562 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009563 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9564 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009565 GEP.setOperand(i, Op);
9566 MadeChange = true;
9567 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009568 }
Chris Lattner28977af2004-04-05 01:30:19 +00009569 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009570 }
Chris Lattner28977af2004-04-05 01:30:19 +00009571 if (MadeChange) return &GEP;
9572
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009573 // If this GEP instruction doesn't move the pointer, and if the input operand
9574 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9575 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009576 if (GEP.hasAllZeroIndices()) {
9577 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9578 // If the bitcast is of an allocation, and the allocation will be
9579 // converted to match the type of the cast, don't touch this.
9580 if (isa<AllocationInst>(BCI->getOperand(0))) {
9581 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009582 if (Instruction *I = visitBitCast(*BCI)) {
9583 if (I != BCI) {
9584 I->takeName(BCI);
9585 BCI->getParent()->getInstList().insert(BCI, I);
9586 ReplaceInstUsesWith(*BCI, I);
9587 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009588 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009589 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009590 }
9591 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9592 }
9593 }
9594
Chris Lattner90ac28c2002-08-02 19:29:35 +00009595 // Combine Indices - If the source pointer to this getelementptr instruction
9596 // is a getelementptr instruction, combine the indices of the two
9597 // getelementptr instructions into a single instruction.
9598 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009599 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009600 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009601 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009602
9603 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009604 // Note that if our source is a gep chain itself that we wait for that
9605 // chain to be resolved before we perform this transformation. This
9606 // avoids us creating a TON of code in some cases.
9607 //
9608 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9609 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9610 return 0; // Wait until our source is folded to completion.
9611
Chris Lattner72588fc2007-02-15 22:48:32 +00009612 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009613
9614 // Find out whether the last index in the source GEP is a sequential idx.
9615 bool EndsWithSequential = false;
9616 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9617 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009618 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009619
Chris Lattner90ac28c2002-08-02 19:29:35 +00009620 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009621 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009622 // Replace: gep (gep %P, long B), long A, ...
9623 // With: T = long A+B; gep %P, T, ...
9624 //
Chris Lattner620ce142004-05-07 22:09:22 +00009625 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009626 if (SO1 == Constant::getNullValue(SO1->getType())) {
9627 Sum = GO1;
9628 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9629 Sum = SO1;
9630 } else {
9631 // If they aren't the same type, convert both to an integer of the
9632 // target's pointer size.
9633 if (SO1->getType() != GO1->getType()) {
9634 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009635 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009636 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009637 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009638 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009639 unsigned PS = TD->getPointerSizeInBits();
9640 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009641 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009642 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009643
Duncan Sands514ab342007-11-01 20:53:16 +00009644 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009645 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009646 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009647 } else {
9648 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009649 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9650 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009651 }
9652 }
9653 }
Chris Lattner620ce142004-05-07 22:09:22 +00009654 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9655 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9656 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009657 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +00009658 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009659 }
Chris Lattner28977af2004-04-05 01:30:19 +00009660 }
Chris Lattner620ce142004-05-07 22:09:22 +00009661
9662 // Recycle the GEP we already have if possible.
9663 if (SrcGEPOperands.size() == 2) {
9664 GEP.setOperand(0, SrcGEPOperands[0]);
9665 GEP.setOperand(1, Sum);
9666 return &GEP;
9667 } else {
9668 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9669 SrcGEPOperands.end()-1);
9670 Indices.push_back(Sum);
9671 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9672 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009673 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009674 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009675 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009676 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009677 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9678 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009679 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9680 }
9681
9682 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009683 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9684 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009685
Chris Lattner620ce142004-05-07 22:09:22 +00009686 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009687 // GEP of global variable. If all of the indices for this GEP are
9688 // constants, we can promote this to a constexpr instead of an instruction.
9689
9690 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009691 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009692 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9693 for (; I != E && isa<Constant>(*I); ++I)
9694 Indices.push_back(cast<Constant>(*I));
9695
9696 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009697 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9698 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009699
9700 // Replace all uses of the GEP with the new constexpr...
9701 return ReplaceInstUsesWith(GEP, CE);
9702 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009703 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009704 if (!isa<PointerType>(X->getType())) {
9705 // Not interesting. Source pointer must be a cast from pointer.
9706 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009707 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9708 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009709 //
9710 // This occurs when the program declares an array extern like "int X[];"
9711 //
9712 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9713 const PointerType *XTy = cast<PointerType>(X->getType());
9714 if (const ArrayType *XATy =
9715 dyn_cast<ArrayType>(XTy->getElementType()))
9716 if (const ArrayType *CATy =
9717 dyn_cast<ArrayType>(CPTy->getElementType()))
9718 if (CATy->getElementType() == XATy->getElementType()) {
9719 // At this point, we know that the cast source type is a pointer
9720 // to an array of the same type as the destination pointer
9721 // array. Because the array type is never stepped over (there
9722 // is a leading zero) we can fold the cast into this GEP.
9723 GEP.setOperand(0, X);
9724 return &GEP;
9725 }
9726 } else if (GEP.getNumOperands() == 2) {
9727 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009728 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9729 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009730 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9731 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9732 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009733 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9734 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009735 Value *Idx[2];
9736 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9737 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009738 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009739 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009740 // V and GEP are both pointer types --> BitCast
9741 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009742 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009743
9744 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009745 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009746 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009747 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009748
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009749 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009750 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009751 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009752
9753 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9754 // allow either a mul, shift, or constant here.
9755 Value *NewIdx = 0;
9756 ConstantInt *Scale = 0;
9757 if (ArrayEltSize == 1) {
9758 NewIdx = GEP.getOperand(1);
9759 Scale = ConstantInt::get(NewIdx->getType(), 1);
9760 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009761 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009762 Scale = CI;
9763 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9764 if (Inst->getOpcode() == Instruction::Shl &&
9765 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009766 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9767 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9768 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009769 NewIdx = Inst->getOperand(0);
9770 } else if (Inst->getOpcode() == Instruction::Mul &&
9771 isa<ConstantInt>(Inst->getOperand(1))) {
9772 Scale = cast<ConstantInt>(Inst->getOperand(1));
9773 NewIdx = Inst->getOperand(0);
9774 }
9775 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009776
Chris Lattner7835cdd2005-09-13 18:36:04 +00009777 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009778 // out, perform the transformation. Note, we don't know whether Scale is
9779 // signed or not. We'll use unsigned version of division/modulo
9780 // operation after making sure Scale doesn't have the sign bit set.
9781 if (Scale && Scale->getSExtValue() >= 0LL &&
9782 Scale->getZExtValue() % ArrayEltSize == 0) {
9783 Scale = ConstantInt::get(Scale->getType(),
9784 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009785 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009786 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009787 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009788 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00009789 NewIdx = InsertNewInstBefore(Sc, GEP);
9790 }
9791
9792 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009793 Value *Idx[2];
9794 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9795 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009796 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009797 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009798 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9799 // The NewGEP must be pointer typed, so must the old one -> BitCast
9800 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009801 }
9802 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009803 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009804 }
9805
Chris Lattner8a2a3112001-12-14 16:52:21 +00009806 return 0;
9807}
9808
Chris Lattner0864acf2002-11-04 16:18:53 +00009809Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9810 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009811 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009812 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9813 const Type *NewTy =
9814 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009815 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009816
9817 // Create and insert the replacement instruction...
9818 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009819 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009820 else {
9821 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009822 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009823 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009824
9825 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009826
Chris Lattner0864acf2002-11-04 16:18:53 +00009827 // Scan to the end of the allocation instructions, to skip over a block of
9828 // allocas if possible...
9829 //
9830 BasicBlock::iterator It = New;
9831 while (isa<AllocationInst>(*It)) ++It;
9832
9833 // Now that I is pointing to the first non-allocation-inst in the block,
9834 // insert our getelementptr instruction...
9835 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009836 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009837 Value *Idx[2];
9838 Idx[0] = NullIdx;
9839 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +00009840 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9841 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009842
9843 // Now make everything use the getelementptr instead of the original
9844 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009845 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009846 } else if (isa<UndefValue>(AI.getArraySize())) {
9847 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009848 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009849 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009850
9851 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9852 // Note that we only do this for alloca's, because malloc should allocate and
9853 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009854 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009855 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009856 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9857
Chris Lattner0864acf2002-11-04 16:18:53 +00009858 return 0;
9859}
9860
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009861Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9862 Value *Op = FI.getOperand(0);
9863
Chris Lattner17be6352004-10-18 02:59:09 +00009864 // free undef -> unreachable.
9865 if (isa<UndefValue>(Op)) {
9866 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009867 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009868 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009869 return EraseInstFromFunction(FI);
9870 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009871
Chris Lattner6160e852004-02-28 04:57:37 +00009872 // If we have 'free null' delete the instruction. This can happen in stl code
9873 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009874 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009875 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009876
9877 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9878 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9879 FI.setOperand(0, CI->getOperand(0));
9880 return &FI;
9881 }
9882
9883 // Change free (gep X, 0,0,0,0) into free(X)
9884 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9885 if (GEPI->hasAllZeroIndices()) {
9886 AddToWorkList(GEPI);
9887 FI.setOperand(0, GEPI->getOperand(0));
9888 return &FI;
9889 }
9890 }
9891
9892 // Change free(malloc) into nothing, if the malloc has a single use.
9893 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9894 if (MI->hasOneUse()) {
9895 EraseInstFromFunction(FI);
9896 return EraseInstFromFunction(*MI);
9897 }
Chris Lattner6160e852004-02-28 04:57:37 +00009898
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009899 return 0;
9900}
9901
9902
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009903/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009904static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009905 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009906 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009907 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009908
Devang Patel99db6ad2007-10-18 19:52:32 +00009909 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9910 // Instead of loading constant c string, use corresponding integer value
9911 // directly if string length is small enough.
9912 const std::string &Str = CE->getOperand(0)->getStringValue();
9913 if (!Str.empty()) {
9914 unsigned len = Str.length();
9915 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9916 unsigned numBits = Ty->getPrimitiveSizeInBits();
9917 // Replace LI with immediate integer store.
9918 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009919 APInt StrVal(numBits, 0);
9920 APInt SingleChar(numBits, 0);
9921 if (TD->isLittleEndian()) {
9922 for (signed i = len-1; i >= 0; i--) {
9923 SingleChar = (uint64_t) Str[i];
9924 StrVal = (StrVal << 8) | SingleChar;
9925 }
9926 } else {
9927 for (unsigned i = 0; i < len; i++) {
9928 SingleChar = (uint64_t) Str[i];
9929 StrVal = (StrVal << 8) | SingleChar;
9930 }
9931 // Append NULL at the end.
9932 SingleChar = 0;
9933 StrVal = (StrVal << 8) | SingleChar;
9934 }
9935 Value *NL = ConstantInt::get(StrVal);
9936 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009937 }
9938 }
9939 }
9940
Chris Lattnerb89e0712004-07-13 01:49:43 +00009941 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009942 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009943 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009944
Reid Spencer42230162007-01-22 05:51:25 +00009945 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009946 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009947 // If the source is an array, the code below will not succeed. Check to
9948 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9949 // constants.
9950 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9951 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9952 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009953 Value *Idxs[2];
9954 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9955 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009956 SrcTy = cast<PointerType>(CastOp->getType());
9957 SrcPTy = SrcTy->getElementType();
9958 }
9959
Reid Spencer42230162007-01-22 05:51:25 +00009960 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009961 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009962 // Do not allow turning this into a load of an integer, which is then
9963 // casted to a pointer, this pessimizes pointer analysis a lot.
9964 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009965 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9966 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009967
Chris Lattnerf9527852005-01-31 04:50:46 +00009968 // Okay, we are casting from one integer or pointer type to another of
9969 // the same size. Instead of casting the pointer before the load, cast
9970 // the result of the loaded value.
9971 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9972 CI->getName(),
9973 LI.isVolatile()),LI);
9974 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009975 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009976 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009977 }
9978 }
9979 return 0;
9980}
9981
Chris Lattnerc10aced2004-09-19 18:43:46 +00009982/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009983/// from this value cannot trap. If it is not obviously safe to load from the
9984/// specified pointer, we do a quick local scan of the basic block containing
9985/// ScanFrom, to determine if the address is already accessed.
9986static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009987 // If it is an alloca it is always safe to load from.
9988 if (isa<AllocaInst>(V)) return true;
9989
Duncan Sands46318cd2007-09-19 10:25:38 +00009990 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009991 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009992 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009993 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009994
9995 // Otherwise, be a little bit agressive by scanning the local block where we
9996 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009997 // from/to. If so, the previous load or store would have already trapped,
9998 // so there is no harm doing an extra load (also, CSE will later eliminate
9999 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010000 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10001
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010002 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010003 --BBI;
10004
10005 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10006 if (LI->getOperand(0) == V) return true;
10007 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10008 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010009
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010010 }
Chris Lattner8a375202004-09-19 19:18:10 +000010011 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010012}
10013
Chris Lattner8d2e8882007-08-11 18:48:48 +000010014/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10015/// until we find the underlying object a pointer is referring to or something
10016/// we don't understand. Note that the returned pointer may be offset from the
10017/// input, because we ignore GEP indices.
10018static Value *GetUnderlyingObject(Value *Ptr) {
10019 while (1) {
10020 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10021 if (CE->getOpcode() == Instruction::BitCast ||
10022 CE->getOpcode() == Instruction::GetElementPtr)
10023 Ptr = CE->getOperand(0);
10024 else
10025 return Ptr;
10026 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10027 Ptr = BCI->getOperand(0);
10028 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10029 Ptr = GEP->getOperand(0);
10030 } else {
10031 return Ptr;
10032 }
10033 }
10034}
10035
Chris Lattner833b8a42003-06-26 05:06:25 +000010036Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10037 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010038
Dan Gohman9941f742007-07-20 16:34:21 +000010039 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010040 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10041 if (KnownAlign >
10042 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10043 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010044 LI.setAlignment(KnownAlign);
10045
Chris Lattner37366c12005-05-01 04:24:53 +000010046 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010047 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010048 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010049 return Res;
10050
10051 // None of the following transforms are legal for volatile loads.
10052 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010053
Chris Lattner62f254d2005-09-12 22:00:15 +000010054 if (&LI.getParent()->front() != &LI) {
10055 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010056 // If the instruction immediately before this is a store to the same
10057 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010058 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10059 if (SI->getOperand(1) == LI.getOperand(0))
10060 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010061 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10062 if (LIB->getOperand(0) == LI.getOperand(0))
10063 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010064 }
Chris Lattner37366c12005-05-01 04:24:53 +000010065
Christopher Lambb15147e2007-12-29 07:56:53 +000010066 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10067 const Value *GEPI0 = GEPI->getOperand(0);
10068 // TODO: Consider a target hook for valid address spaces for this xform.
10069 if (isa<ConstantPointerNull>(GEPI0) &&
10070 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010071 // Insert a new store to null instruction before the load to indicate
10072 // that this code is not reachable. We do this instead of inserting
10073 // an unreachable instruction directly because we cannot modify the
10074 // CFG.
10075 new StoreInst(UndefValue::get(LI.getType()),
10076 Constant::getNullValue(Op->getType()), &LI);
10077 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10078 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010079 }
Chris Lattner37366c12005-05-01 04:24:53 +000010080
Chris Lattnere87597f2004-10-16 18:11:37 +000010081 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010082 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010083 // TODO: Consider a target hook for valid address spaces for this xform.
10084 if (isa<UndefValue>(C) || (C->isNullValue() &&
10085 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010086 // Insert a new store to null instruction before the load to indicate that
10087 // this code is not reachable. We do this instead of inserting an
10088 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010089 new StoreInst(UndefValue::get(LI.getType()),
10090 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010091 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010092 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010093
Chris Lattnere87597f2004-10-16 18:11:37 +000010094 // Instcombine load (constant global) into the value loaded.
10095 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010096 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010097 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010098
Chris Lattnere87597f2004-10-16 18:11:37 +000010099 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010100 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010101 if (CE->getOpcode() == Instruction::GetElementPtr) {
10102 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010103 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010104 if (Constant *V =
10105 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010106 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010107 if (CE->getOperand(0)->isNullValue()) {
10108 // Insert a new store to null instruction before the load to indicate
10109 // that this code is not reachable. We do this instead of inserting
10110 // an unreachable instruction directly because we cannot modify the
10111 // CFG.
10112 new StoreInst(UndefValue::get(LI.getType()),
10113 Constant::getNullValue(Op->getType()), &LI);
10114 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10115 }
10116
Reid Spencer3da59db2006-11-27 01:05:10 +000010117 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010118 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010119 return Res;
10120 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010121 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010122 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010123
10124 // If this load comes from anywhere in a constant global, and if the global
10125 // is all undef or zero, we know what it loads.
10126 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10127 if (GV->isConstant() && GV->hasInitializer()) {
10128 if (GV->getInitializer()->isNullValue())
10129 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10130 else if (isa<UndefValue>(GV->getInitializer()))
10131 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10132 }
10133 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010134
Chris Lattner37366c12005-05-01 04:24:53 +000010135 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010136 // Change select and PHI nodes to select values instead of addresses: this
10137 // helps alias analysis out a lot, allows many others simplifications, and
10138 // exposes redundancy in the code.
10139 //
10140 // Note that we cannot do the transformation unless we know that the
10141 // introduced loads cannot trap! Something like this is valid as long as
10142 // the condition is always false: load (select bool %C, int* null, int* %G),
10143 // but it would not be valid if we transformed it to load from null
10144 // unconditionally.
10145 //
10146 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10147 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010148 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10149 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010150 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010151 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010152 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010153 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010154 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010155 }
10156
Chris Lattner684fe212004-09-23 15:46:00 +000010157 // load (select (cond, null, P)) -> load P
10158 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10159 if (C->isNullValue()) {
10160 LI.setOperand(0, SI->getOperand(2));
10161 return &LI;
10162 }
10163
10164 // load (select (cond, P, null)) -> load P
10165 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10166 if (C->isNullValue()) {
10167 LI.setOperand(0, SI->getOperand(1));
10168 return &LI;
10169 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010170 }
10171 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010172 return 0;
10173}
10174
Reid Spencer55af2b52007-01-19 21:20:31 +000010175/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010176/// when possible.
10177static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10178 User *CI = cast<User>(SI.getOperand(1));
10179 Value *CastOp = CI->getOperand(0);
10180
10181 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10182 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10183 const Type *SrcPTy = SrcTy->getElementType();
10184
Reid Spencer42230162007-01-22 05:51:25 +000010185 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010186 // If the source is an array, the code below will not succeed. Check to
10187 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10188 // constants.
10189 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10190 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10191 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010192 Value* Idxs[2];
10193 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10194 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010195 SrcTy = cast<PointerType>(CastOp->getType());
10196 SrcPTy = SrcTy->getElementType();
10197 }
10198
Reid Spencer67f827c2007-01-20 23:35:48 +000010199 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10200 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10201 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010202
10203 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010204 // the same size. Instead of casting the pointer before
10205 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010206 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010207 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010208 Instruction::CastOps opcode = Instruction::BitCast;
10209 const Type* CastSrcTy = SIOp0->getType();
10210 const Type* CastDstTy = SrcPTy;
10211 if (isa<PointerType>(CastDstTy)) {
10212 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010213 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010214 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010215 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010216 opcode = Instruction::PtrToInt;
10217 }
10218 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010219 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010220 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010221 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010222 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010223 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010224 return new StoreInst(NewCast, CastOp);
10225 }
10226 }
10227 }
10228 return 0;
10229}
10230
Chris Lattner2f503e62005-01-31 05:36:43 +000010231Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10232 Value *Val = SI.getOperand(0);
10233 Value *Ptr = SI.getOperand(1);
10234
10235 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010236 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010237 ++NumCombined;
10238 return 0;
10239 }
Chris Lattner836692d2007-01-15 06:51:56 +000010240
10241 // If the RHS is an alloca with a single use, zapify the store, making the
10242 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010243 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010244 if (isa<AllocaInst>(Ptr)) {
10245 EraseInstFromFunction(SI);
10246 ++NumCombined;
10247 return 0;
10248 }
10249
10250 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10251 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10252 GEP->getOperand(0)->hasOneUse()) {
10253 EraseInstFromFunction(SI);
10254 ++NumCombined;
10255 return 0;
10256 }
10257 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010258
Dan Gohman9941f742007-07-20 16:34:21 +000010259 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010260 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10261 if (KnownAlign >
10262 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10263 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010264 SI.setAlignment(KnownAlign);
10265
Chris Lattner9ca96412006-02-08 03:25:32 +000010266 // Do really simple DSE, to catch cases where there are several consequtive
10267 // stores to the same location, separated by a few arithmetic operations. This
10268 // situation often occurs with bitfield accesses.
10269 BasicBlock::iterator BBI = &SI;
10270 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10271 --ScanInsts) {
10272 --BBI;
10273
10274 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10275 // Prev store isn't volatile, and stores to the same location?
10276 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10277 ++NumDeadStore;
10278 ++BBI;
10279 EraseInstFromFunction(*PrevSI);
10280 continue;
10281 }
10282 break;
10283 }
10284
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010285 // If this is a load, we have to stop. However, if the loaded value is from
10286 // the pointer we're loading and is producing the pointer we're storing,
10287 // then *this* store is dead (X = load P; store X -> P).
10288 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010289 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010290 EraseInstFromFunction(SI);
10291 ++NumCombined;
10292 return 0;
10293 }
10294 // Otherwise, this is a load from some other location. Stores before it
10295 // may not be dead.
10296 break;
10297 }
10298
Chris Lattner9ca96412006-02-08 03:25:32 +000010299 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010300 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010301 break;
10302 }
10303
10304
10305 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010306
10307 // store X, null -> turns into 'unreachable' in SimplifyCFG
10308 if (isa<ConstantPointerNull>(Ptr)) {
10309 if (!isa<UndefValue>(Val)) {
10310 SI.setOperand(0, UndefValue::get(Val->getType()));
10311 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010312 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010313 ++NumCombined;
10314 }
10315 return 0; // Do not modify these!
10316 }
10317
10318 // store undef, Ptr -> noop
10319 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010320 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010321 ++NumCombined;
10322 return 0;
10323 }
10324
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010325 // If the pointer destination is a cast, see if we can fold the cast into the
10326 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010327 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010328 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10329 return Res;
10330 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010331 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010332 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10333 return Res;
10334
Chris Lattner408902b2005-09-12 23:23:25 +000010335
10336 // If this store is the last instruction in the basic block, and if the block
10337 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010338 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010339 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010340 if (BI->isUnconditional())
10341 if (SimplifyStoreAtEndOfBlock(SI))
10342 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010343
Chris Lattner2f503e62005-01-31 05:36:43 +000010344 return 0;
10345}
10346
Chris Lattner3284d1f2007-04-15 00:07:55 +000010347/// SimplifyStoreAtEndOfBlock - Turn things like:
10348/// if () { *P = v1; } else { *P = v2 }
10349/// into a phi node with a store in the successor.
10350///
Chris Lattner31755a02007-04-15 01:02:18 +000010351/// Simplify things like:
10352/// *P = v1; if () { *P = v2; }
10353/// into a phi node with a store in the successor.
10354///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010355bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10356 BasicBlock *StoreBB = SI.getParent();
10357
10358 // Check to see if the successor block has exactly two incoming edges. If
10359 // so, see if the other predecessor contains a store to the same location.
10360 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010361 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010362
10363 // Determine whether Dest has exactly two predecessors and, if so, compute
10364 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010365 pred_iterator PI = pred_begin(DestBB);
10366 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010367 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010368 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010369 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010370 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010371 return false;
10372
10373 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010374 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010375 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010376 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010377 }
Chris Lattner31755a02007-04-15 01:02:18 +000010378 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010379 return false;
10380
10381
Chris Lattner31755a02007-04-15 01:02:18 +000010382 // Verify that the other block ends in a branch and is not otherwise empty.
10383 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010384 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010385 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010386 return false;
10387
Chris Lattner31755a02007-04-15 01:02:18 +000010388 // If the other block ends in an unconditional branch, check for the 'if then
10389 // else' case. there is an instruction before the branch.
10390 StoreInst *OtherStore = 0;
10391 if (OtherBr->isUnconditional()) {
10392 // If this isn't a store, or isn't a store to the same location, bail out.
10393 --BBI;
10394 OtherStore = dyn_cast<StoreInst>(BBI);
10395 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10396 return false;
10397 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010398 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010399 // destinations is StoreBB, then we have the if/then case.
10400 if (OtherBr->getSuccessor(0) != StoreBB &&
10401 OtherBr->getSuccessor(1) != StoreBB)
10402 return false;
10403
10404 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010405 // if/then triangle. See if there is a store to the same ptr as SI that
10406 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010407 for (;; --BBI) {
10408 // Check to see if we find the matching store.
10409 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10410 if (OtherStore->getOperand(1) != SI.getOperand(1))
10411 return false;
10412 break;
10413 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010414 // If we find something that may be using the stored value, or if we run
10415 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010416 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10417 BBI == OtherBB->begin())
10418 return false;
10419 }
10420
10421 // In order to eliminate the store in OtherBr, we have to
10422 // make sure nothing reads the stored value in StoreBB.
10423 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10424 // FIXME: This should really be AA driven.
10425 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10426 return false;
10427 }
10428 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010429
Chris Lattner31755a02007-04-15 01:02:18 +000010430 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010431 Value *MergedVal = OtherStore->getOperand(0);
10432 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010433 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010434 PN->reserveOperandSpace(2);
10435 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010436 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10437 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010438 }
10439
10440 // Advance to a place where it is safe to insert the new store and
10441 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000010442 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010443 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10444 OtherStore->isVolatile()), *BBI);
10445
10446 // Nuke the old stores.
10447 EraseInstFromFunction(SI);
10448 EraseInstFromFunction(*OtherStore);
10449 ++NumCombined;
10450 return true;
10451}
10452
Chris Lattner2f503e62005-01-31 05:36:43 +000010453
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010454Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10455 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010456 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010457 BasicBlock *TrueDest;
10458 BasicBlock *FalseDest;
10459 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10460 !isa<Constant>(X)) {
10461 // Swap Destinations and condition...
10462 BI.setCondition(X);
10463 BI.setSuccessor(0, FalseDest);
10464 BI.setSuccessor(1, TrueDest);
10465 return &BI;
10466 }
10467
Reid Spencere4d87aa2006-12-23 06:05:41 +000010468 // Cannonicalize fcmp_one -> fcmp_oeq
10469 FCmpInst::Predicate FPred; Value *Y;
10470 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10471 TrueDest, FalseDest)))
10472 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10473 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10474 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010475 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010476 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10477 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010478 // Swap Destinations and condition...
10479 BI.setCondition(NewSCC);
10480 BI.setSuccessor(0, FalseDest);
10481 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010482 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010483 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010484 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010485 return &BI;
10486 }
10487
10488 // Cannonicalize icmp_ne -> icmp_eq
10489 ICmpInst::Predicate IPred;
10490 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10491 TrueDest, FalseDest)))
10492 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10493 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10494 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10495 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010496 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010497 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10498 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010499 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010500 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010501 BI.setSuccessor(0, FalseDest);
10502 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010503 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010504 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010505 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010506 return &BI;
10507 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010508
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010509 return 0;
10510}
Chris Lattner0864acf2002-11-04 16:18:53 +000010511
Chris Lattner46238a62004-07-03 00:26:11 +000010512Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10513 Value *Cond = SI.getCondition();
10514 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10515 if (I->getOpcode() == Instruction::Add)
10516 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10517 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10518 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010519 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010520 AddRHS));
10521 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010522 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010523 return &SI;
10524 }
10525 }
10526 return 0;
10527}
10528
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010529// This is the recursive version of BuildSubAggregate. It takes a few different
10530// arguments. Idxs is the index within the nested struct From that we are
10531// looking at now (which is of type IndexedType). IdxSkip is the number of
10532// indices from Idxs that should be left out when inserting into the resulting
10533// struct. To is the result struct built so far, new insertvalue instructions
10534// build on that.
10535Value *InstCombiner::BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
10536 SmallVector<unsigned, 10> &Idxs,
10537 unsigned IdxSkip,
10538 Instruction &InsertBefore) {
10539 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
10540 if (STy) {
10541 // General case, the type indexed by Idxs is a struct
10542 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
10543 // Process each struct element recursively
10544 Idxs.push_back(i);
10545 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip, InsertBefore);
10546 Idxs.pop_back();
10547 }
10548 return To;
10549 } else {
10550 // Base case, the type indexed by SourceIdxs is not a struct
10551 // Load the value from the nested struct into the sub struct (and skip
10552 // IdxSkip indices when indexing the sub struct).
10553 Instruction *V = llvm::ExtractValueInst::Create(From, Idxs.begin(), Idxs.end(), "tmp");
10554 InsertNewInstBefore(V, InsertBefore);
10555 Instruction *Ins = llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip, Idxs.end(), "tmp");
10556 InsertNewInstBefore(Ins, InsertBefore);
10557 return Ins;
10558 }
10559}
10560
10561// This helper takes a nested struct and extracts a part of it (which is again a
10562// struct) into a new value. For example, given the struct:
10563// { a, { b, { c, d }, e } }
10564// and the indices "1, 1" this returns
10565// { c, d }.
10566//
10567// It does this by inserting an extractvalue and insertvalue for each element in
10568// the resulting struct, as opposed to just inserting a single struct. This
10569// allows for later folding of these individual extractvalue instructions with
10570// insertvalue instructions that fill the nested struct.
10571//
10572// Any inserted instructions are inserted before InsertBefore
10573Value *InstCombiner::BuildSubAggregate(Value *From, const unsigned *idx_begin, const unsigned *idx_end, Instruction &InsertBefore) {
10574 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(), idx_begin, idx_end);
10575 Value *To = UndefValue::get(IndexedType);
10576 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
10577 unsigned IdxSkip = Idxs.size();
10578
10579 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
10580}
10581
10582/// FindScalarValue - Given an aggregrate and an sequence of indices, see if the
10583/// scalar value indexed is already around as a register, for example if it were
10584/// inserted directly into the aggregrate.
10585Value *InstCombiner::FindScalarValue(Value *V, const unsigned *idx_begin,
10586 const unsigned *idx_end, Instruction &InsertBefore) {
10587 // Nothing to index? Just return V then (this is useful at the end of our
10588 // recursion)
10589 if (idx_begin == idx_end)
10590 return V;
10591 // We have indices, so V should have an indexable type
10592 assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType()))
10593 && "Not looking at a struct or array?");
10594 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
10595 && "Invalid indices for type?");
10596 const CompositeType *PTy = cast<CompositeType>(V->getType());
10597
10598 if (isa<UndefValue>(V))
10599 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
10600 idx_begin,
10601 idx_end));
10602 else if (isa<ConstantAggregateZero>(V))
10603 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
10604 idx_begin,
10605 idx_end));
10606 else if (Constant *C = dyn_cast<Constant>(V)) {
10607 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
10608 // Recursively process this constant
10609 return FindScalarValue(C->getOperand(*idx_begin), ++idx_begin, idx_end, InsertBefore);
10610 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
10611 // Loop the indices for the insertvalue instruction in parallel with the
10612 // requested indices
10613 const unsigned *req_idx = idx_begin;
10614 for (const unsigned *i = I->idx_begin(), *e = I->idx_end(); i != e; ++i, ++req_idx) {
10615 if (req_idx == idx_end)
10616 // The requested index is a part of a nested aggregate. Handle this
10617 // specially.
10618 return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
10619
10620 // This insert value inserts something else than what we are looking for.
10621 // See if the (aggregrate) value inserted into has the value we are
10622 // looking for, then.
10623 if (*req_idx != *i)
10624 return FindScalarValue(I->getAggregateOperand(), idx_begin, idx_end, InsertBefore);
10625 }
10626 // If we end up here, the indices of the insertvalue match with those
10627 // requested (though possibly only partially). Now we recursively look at
10628 // the inserted value, passing any remaining indices.
10629 return FindScalarValue(I->getInsertedValueOperand(), req_idx, idx_end, InsertBefore);
10630 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
10631 // If we're extracting a value from an aggregrate that was extracted from
10632 // something else, we can extract from that something else directly instead.
10633 // However, we will need to chain I's indices with the requested indices.
10634
10635 // Calculate the number of indices required
10636 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
10637 // Allocate some space to put the new indices in
10638 unsigned *new_begin = new unsigned[size];
10639 // Auto cleanup this array
10640 std::auto_ptr<unsigned> newptr(new_begin);
10641 // Start inserting at the beginning
10642 unsigned *new_end = new_begin;
10643 // Add indices from the extract value instruction
10644 for (const unsigned *i = I->idx_begin(), *e = I->idx_end(); i != e; ++i, ++new_end)
10645 *new_end = *i;
10646
10647 // Add requested indices
10648 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i, ++new_end)
10649 *new_end = *i;
10650
10651 assert((unsigned)(new_end - new_begin) == size && "Number of indices added not correct?");
10652
10653 return FindScalarValue(I->getAggregateOperand(), new_begin, new_end, InsertBefore);
10654 }
10655 // Otherwise, we don't know (such as, extracting from a function return value
10656 // or load instruction)
10657 return 0;
10658}
10659
10660Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10661 // See if we are trying to extract a known value. If so, use that instead.
10662 if (Value *Elt = FindScalarValue(EV.getOperand(0), EV.idx_begin(), EV.idx_end(), EV))
10663 return ReplaceInstUsesWith(EV, Elt);
10664
10665 // No changes
10666 return 0;
10667}
10668
Chris Lattner220b0cf2006-03-05 00:22:33 +000010669/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10670/// is to leave as a vector operation.
10671static bool CheapToScalarize(Value *V, bool isConstant) {
10672 if (isa<ConstantAggregateZero>(V))
10673 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010674 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010675 if (isConstant) return true;
10676 // If all elts are the same, we can extract.
10677 Constant *Op0 = C->getOperand(0);
10678 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10679 if (C->getOperand(i) != Op0)
10680 return false;
10681 return true;
10682 }
10683 Instruction *I = dyn_cast<Instruction>(V);
10684 if (!I) return false;
10685
10686 // Insert element gets simplified to the inserted element or is deleted if
10687 // this is constant idx extract element and its a constant idx insertelt.
10688 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10689 isa<ConstantInt>(I->getOperand(2)))
10690 return true;
10691 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10692 return true;
10693 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10694 if (BO->hasOneUse() &&
10695 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10696 CheapToScalarize(BO->getOperand(1), isConstant)))
10697 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010698 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10699 if (CI->hasOneUse() &&
10700 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10701 CheapToScalarize(CI->getOperand(1), isConstant)))
10702 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010703
10704 return false;
10705}
10706
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010707/// Read and decode a shufflevector mask.
10708///
10709/// It turns undef elements into values that are larger than the number of
10710/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010711static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10712 unsigned NElts = SVI->getType()->getNumElements();
10713 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10714 return std::vector<unsigned>(NElts, 0);
10715 if (isa<UndefValue>(SVI->getOperand(2)))
10716 return std::vector<unsigned>(NElts, 2*NElts);
10717
10718 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010719 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010720 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10721 if (isa<UndefValue>(CP->getOperand(i)))
10722 Result.push_back(NElts*2); // undef -> 8
10723 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010724 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010725 return Result;
10726}
10727
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010728/// FindScalarElement - Given a vector and an element number, see if the scalar
10729/// value is already around as a register, for example if it were inserted then
10730/// extracted from the vector.
10731static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010732 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10733 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010734 unsigned Width = PTy->getNumElements();
10735 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010736 return UndefValue::get(PTy->getElementType());
10737
10738 if (isa<UndefValue>(V))
10739 return UndefValue::get(PTy->getElementType());
10740 else if (isa<ConstantAggregateZero>(V))
10741 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010742 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010743 return CP->getOperand(EltNo);
10744 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10745 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010746 if (!isa<ConstantInt>(III->getOperand(2)))
10747 return 0;
10748 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010749
10750 // If this is an insert to the element we are looking for, return the
10751 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010752 if (EltNo == IIElt)
10753 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010754
10755 // Otherwise, the insertelement doesn't modify the value, recurse on its
10756 // vector input.
10757 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010758 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010759 unsigned InEl = getShuffleMask(SVI)[EltNo];
10760 if (InEl < Width)
10761 return FindScalarElement(SVI->getOperand(0), InEl);
10762 else if (InEl < Width*2)
10763 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10764 else
10765 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010766 }
10767
10768 // Otherwise, we don't know.
10769 return 0;
10770}
10771
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010772Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000010773 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010774 if (isa<UndefValue>(EI.getOperand(0)))
10775 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10776
Dan Gohman07a96762007-07-16 14:29:03 +000010777 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010778 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10779 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10780
Reid Spencer9d6565a2007-02-15 02:26:10 +000010781 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000010782 // If vector val is constant with all elements the same, replace EI with
10783 // that element. When the elements are not identical, we cannot replace yet
10784 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000010785 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010786 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010787 if (C->getOperand(i) != op0) {
10788 op0 = 0;
10789 break;
10790 }
10791 if (op0)
10792 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010793 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010794
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010795 // If extracting a specified index from the vector, see if we can recursively
10796 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010797 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010798 unsigned IndexVal = IdxC->getZExtValue();
10799 unsigned VectorWidth =
10800 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10801
10802 // If this is extracting an invalid index, turn this into undef, to avoid
10803 // crashing the code below.
10804 if (IndexVal >= VectorWidth)
10805 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10806
Chris Lattner867b99f2006-10-05 06:55:50 +000010807 // This instruction only demands the single element from the input vector.
10808 // If the input vector has a single use, simplify it based on this use
10809 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010810 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010811 uint64_t UndefElts;
10812 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010813 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010814 UndefElts)) {
10815 EI.setOperand(0, V);
10816 return &EI;
10817 }
10818 }
10819
Reid Spencerb83eb642006-10-20 07:07:24 +000010820 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010821 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010822
10823 // If the this extractelement is directly using a bitcast from a vector of
10824 // the same number of elements, see if we can find the source element from
10825 // it. In this case, we will end up needing to bitcast the scalars.
10826 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10827 if (const VectorType *VT =
10828 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10829 if (VT->getNumElements() == VectorWidth)
10830 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10831 return new BitCastInst(Elt, EI.getType());
10832 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010833 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010834
Chris Lattner73fa49d2006-05-25 22:53:38 +000010835 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010836 if (I->hasOneUse()) {
10837 // Push extractelement into predecessor operation if legal and
10838 // profitable to do so
10839 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010840 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10841 if (CheapToScalarize(BO, isConstantElt)) {
10842 ExtractElementInst *newEI0 =
10843 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10844 EI.getName()+".lhs");
10845 ExtractElementInst *newEI1 =
10846 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10847 EI.getName()+".rhs");
10848 InsertNewInstBefore(newEI0, EI);
10849 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010850 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000010851 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010852 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010853 unsigned AS =
10854 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010855 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10856 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010857 GetElementPtrInst *GEP =
10858 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010859 InsertNewInstBefore(GEP, EI);
10860 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010861 }
10862 }
10863 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10864 // Extracting the inserted element?
10865 if (IE->getOperand(2) == EI.getOperand(1))
10866 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10867 // If the inserted and extracted elements are constants, they must not
10868 // be the same value, extract from the pre-inserted value instead.
10869 if (isa<Constant>(IE->getOperand(2)) &&
10870 isa<Constant>(EI.getOperand(1))) {
10871 AddUsesToWorkList(EI);
10872 EI.setOperand(0, IE->getOperand(0));
10873 return &EI;
10874 }
10875 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10876 // If this is extracting an element from a shufflevector, figure out where
10877 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010878 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10879 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010880 Value *Src;
10881 if (SrcIdx < SVI->getType()->getNumElements())
10882 Src = SVI->getOperand(0);
10883 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10884 SrcIdx -= SVI->getType()->getNumElements();
10885 Src = SVI->getOperand(1);
10886 } else {
10887 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010888 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010889 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010890 }
10891 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010892 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010893 return 0;
10894}
10895
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010896/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10897/// elements from either LHS or RHS, return the shuffle mask and true.
10898/// Otherwise, return false.
10899static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10900 std::vector<Constant*> &Mask) {
10901 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10902 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010903 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010904
10905 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010906 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010907 return true;
10908 } else if (V == LHS) {
10909 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010910 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010911 return true;
10912 } else if (V == RHS) {
10913 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010914 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010915 return true;
10916 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10917 // If this is an insert of an extract from some other vector, include it.
10918 Value *VecOp = IEI->getOperand(0);
10919 Value *ScalarOp = IEI->getOperand(1);
10920 Value *IdxOp = IEI->getOperand(2);
10921
Chris Lattnerd929f062006-04-27 21:14:21 +000010922 if (!isa<ConstantInt>(IdxOp))
10923 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010924 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010925
10926 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10927 // Okay, we can handle this if the vector we are insertinting into is
10928 // transitively ok.
10929 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10930 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010931 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010932 return true;
10933 }
10934 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10935 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010936 EI->getOperand(0)->getType() == V->getType()) {
10937 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010938 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010939
10940 // This must be extracting from either LHS or RHS.
10941 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10942 // Okay, we can handle this if the vector we are insertinting into is
10943 // transitively ok.
10944 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10945 // If so, update the mask to reflect the inserted value.
10946 if (EI->getOperand(0) == LHS) {
10947 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010948 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010949 } else {
10950 assert(EI->getOperand(0) == RHS);
10951 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010952 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010953
10954 }
10955 return true;
10956 }
10957 }
10958 }
10959 }
10960 }
10961 // TODO: Handle shufflevector here!
10962
10963 return false;
10964}
10965
10966/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10967/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10968/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010969static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010970 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010971 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010972 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010973 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010974 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010975
10976 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010977 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010978 return V;
10979 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010980 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010981 return V;
10982 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10983 // If this is an insert of an extract from some other vector, include it.
10984 Value *VecOp = IEI->getOperand(0);
10985 Value *ScalarOp = IEI->getOperand(1);
10986 Value *IdxOp = IEI->getOperand(2);
10987
10988 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10989 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10990 EI->getOperand(0)->getType() == V->getType()) {
10991 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010992 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10993 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010994
10995 // Either the extracted from or inserted into vector must be RHSVec,
10996 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010997 if (EI->getOperand(0) == RHS || RHS == 0) {
10998 RHS = EI->getOperand(0);
10999 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011000 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011001 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011002 return V;
11003 }
11004
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011005 if (VecOp == RHS) {
11006 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011007 // Everything but the extracted element is replaced with the RHS.
11008 for (unsigned i = 0; i != NumElts; ++i) {
11009 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011010 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011011 }
11012 return V;
11013 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011014
11015 // If this insertelement is a chain that comes from exactly these two
11016 // vectors, return the vector and the effective shuffle.
11017 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11018 return EI->getOperand(0);
11019
Chris Lattnerefb47352006-04-15 01:39:45 +000011020 }
11021 }
11022 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011023 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011024
11025 // Otherwise, can't do anything fancy. Return an identity vector.
11026 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011027 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011028 return V;
11029}
11030
11031Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11032 Value *VecOp = IE.getOperand(0);
11033 Value *ScalarOp = IE.getOperand(1);
11034 Value *IdxOp = IE.getOperand(2);
11035
Chris Lattner599ded12007-04-09 01:11:16 +000011036 // Inserting an undef or into an undefined place, remove this.
11037 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11038 ReplaceInstUsesWith(IE, VecOp);
11039
Chris Lattnerefb47352006-04-15 01:39:45 +000011040 // If the inserted element was extracted from some other vector, and if the
11041 // indexes are constant, try to turn this into a shufflevector operation.
11042 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11043 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11044 EI->getOperand(0)->getType() == IE.getType()) {
11045 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011046 unsigned ExtractedIdx =
11047 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011048 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011049
11050 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11051 return ReplaceInstUsesWith(IE, VecOp);
11052
11053 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11054 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11055
11056 // If we are extracting a value from a vector, then inserting it right
11057 // back into the same place, just use the input vector.
11058 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11059 return ReplaceInstUsesWith(IE, VecOp);
11060
11061 // We could theoretically do this for ANY input. However, doing so could
11062 // turn chains of insertelement instructions into a chain of shufflevector
11063 // instructions, and right now we do not merge shufflevectors. As such,
11064 // only do this in a situation where it is clear that there is benefit.
11065 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11066 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11067 // the values of VecOp, except then one read from EIOp0.
11068 // Build a new shuffle mask.
11069 std::vector<Constant*> Mask;
11070 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011071 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011072 else {
11073 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011074 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011075 NumVectorElts));
11076 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011077 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011078 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011079 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011080 }
11081
11082 // If this insertelement isn't used by some other insertelement, turn it
11083 // (and any insertelements it points to), into one big shuffle.
11084 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11085 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011086 Value *RHS = 0;
11087 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11088 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11089 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011090 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011091 }
11092 }
11093 }
11094
11095 return 0;
11096}
11097
11098
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011099Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11100 Value *LHS = SVI.getOperand(0);
11101 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011102 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011103
11104 bool MadeChange = false;
11105
Chris Lattner867b99f2006-10-05 06:55:50 +000011106 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011107 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011108 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11109
Chris Lattnere4929dd2007-01-05 07:36:08 +000011110 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011111 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011112 if (isa<UndefValue>(SVI.getOperand(1))) {
11113 // Scan to see if there are any references to the RHS. If so, replace them
11114 // with undef element refs and set MadeChange to true.
11115 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11116 if (Mask[i] >= e && Mask[i] != 2*e) {
11117 Mask[i] = 2*e;
11118 MadeChange = true;
11119 }
11120 }
11121
11122 if (MadeChange) {
11123 // Remap any references to RHS to use LHS.
11124 std::vector<Constant*> Elts;
11125 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11126 if (Mask[i] == 2*e)
11127 Elts.push_back(UndefValue::get(Type::Int32Ty));
11128 else
11129 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11130 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011131 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011132 }
11133 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011134
Chris Lattner863bcff2006-05-25 23:48:38 +000011135 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11136 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11137 if (LHS == RHS || isa<UndefValue>(LHS)) {
11138 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011139 // shuffle(undef,undef,mask) -> undef.
11140 return ReplaceInstUsesWith(SVI, LHS);
11141 }
11142
Chris Lattner863bcff2006-05-25 23:48:38 +000011143 // Remap any references to RHS to use LHS.
11144 std::vector<Constant*> Elts;
11145 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011146 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011147 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011148 else {
11149 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11150 (Mask[i] < e && isa<UndefValue>(LHS)))
11151 Mask[i] = 2*e; // Turn into undef.
11152 else
11153 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011154 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011155 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011156 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011157 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011158 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011159 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011160 LHS = SVI.getOperand(0);
11161 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011162 MadeChange = true;
11163 }
11164
Chris Lattner7b2e27922006-05-26 00:29:06 +000011165 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011166 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011167
Chris Lattner863bcff2006-05-25 23:48:38 +000011168 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11169 if (Mask[i] >= e*2) continue; // Ignore undef values.
11170 // Is this an identity shuffle of the LHS value?
11171 isLHSID &= (Mask[i] == i);
11172
11173 // Is this an identity shuffle of the RHS value?
11174 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011175 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011176
Chris Lattner863bcff2006-05-25 23:48:38 +000011177 // Eliminate identity shuffles.
11178 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11179 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011180
Chris Lattner7b2e27922006-05-26 00:29:06 +000011181 // If the LHS is a shufflevector itself, see if we can combine it with this
11182 // one without producing an unusual shuffle. Here we are really conservative:
11183 // we are absolutely afraid of producing a shuffle mask not in the input
11184 // program, because the code gen may not be smart enough to turn a merged
11185 // shuffle into two specific shuffles: it may produce worse code. As such,
11186 // we only merge two shuffles if the result is one of the two input shuffle
11187 // masks. In this case, merging the shuffles just removes one instruction,
11188 // which we know is safe. This is good for things like turning:
11189 // (splat(splat)) -> splat.
11190 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11191 if (isa<UndefValue>(RHS)) {
11192 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11193
11194 std::vector<unsigned> NewMask;
11195 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11196 if (Mask[i] >= 2*e)
11197 NewMask.push_back(2*e);
11198 else
11199 NewMask.push_back(LHSMask[Mask[i]]);
11200
11201 // If the result mask is equal to the src shuffle or this shuffle mask, do
11202 // the replacement.
11203 if (NewMask == LHSMask || NewMask == Mask) {
11204 std::vector<Constant*> Elts;
11205 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11206 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011207 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011208 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011209 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011210 }
11211 }
11212 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11213 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011214 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011215 }
11216 }
11217 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011218
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011219 return MadeChange ? &SVI : 0;
11220}
11221
11222
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011223
Chris Lattnerea1c4542004-12-08 23:43:58 +000011224
11225/// TryToSinkInstruction - Try to move the specified instruction from its
11226/// current block into the beginning of DestBlock, which can only happen if it's
11227/// safe to move the instruction past all of the instructions between it and the
11228/// end of its block.
11229static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11230 assert(I->hasOneUse() && "Invariants didn't hold!");
11231
Chris Lattner108e9022005-10-27 17:13:11 +000011232 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011233 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11234 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011235
Chris Lattnerea1c4542004-12-08 23:43:58 +000011236 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011237 if (isa<AllocaInst>(I) && I->getParent() ==
11238 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011239 return false;
11240
Chris Lattner96a52a62004-12-09 07:14:34 +000011241 // We can only sink load instructions if there is nothing between the load and
11242 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011243 if (I->mayReadFromMemory()) {
11244 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011245 Scan != E; ++Scan)
11246 if (Scan->mayWriteToMemory())
11247 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011248 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011249
Dan Gohman02dea8b2008-05-23 21:05:58 +000011250 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011251
Chris Lattner4bc5f802005-08-08 19:11:57 +000011252 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011253 ++NumSunkInst;
11254 return true;
11255}
11256
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011257
11258/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11259/// all reachable code to the worklist.
11260///
11261/// This has a couple of tricks to make the code faster and more powerful. In
11262/// particular, we constant fold and DCE instructions as we go, to avoid adding
11263/// them to the worklist (this significantly speeds up instcombine on code where
11264/// many instructions are dead or constant). Additionally, if we find a branch
11265/// whose condition is a known constant, we only visit the reachable successors.
11266///
11267static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011268 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011269 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011270 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011271 std::vector<BasicBlock*> Worklist;
11272 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011273
Chris Lattner2c7718a2007-03-23 19:17:18 +000011274 while (!Worklist.empty()) {
11275 BB = Worklist.back();
11276 Worklist.pop_back();
11277
11278 // We have now visited this block! If we've already been here, ignore it.
11279 if (!Visited.insert(BB)) continue;
11280
11281 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11282 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011283
Chris Lattner2c7718a2007-03-23 19:17:18 +000011284 // DCE instruction if trivially dead.
11285 if (isInstructionTriviallyDead(Inst)) {
11286 ++NumDeadInst;
11287 DOUT << "IC: DCE: " << *Inst;
11288 Inst->eraseFromParent();
11289 continue;
11290 }
11291
11292 // ConstantProp instruction if trivially constant.
11293 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11294 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11295 Inst->replaceAllUsesWith(C);
11296 ++NumConstProp;
11297 Inst->eraseFromParent();
11298 continue;
11299 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011300
Chris Lattner2c7718a2007-03-23 19:17:18 +000011301 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011302 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011303
11304 // Recursively visit successors. If this is a branch or switch on a
11305 // constant, only visit the reachable successor.
11306 TerminatorInst *TI = BB->getTerminator();
11307 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11308 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11309 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011310 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011311 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011312 continue;
11313 }
11314 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11315 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11316 // See if this is an explicit destination.
11317 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11318 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011319 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011320 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011321 continue;
11322 }
11323
11324 // Otherwise it is the default destination.
11325 Worklist.push_back(SI->getSuccessor(0));
11326 continue;
11327 }
11328 }
11329
11330 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11331 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011332 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011333}
11334
Chris Lattnerec9c3582007-03-03 02:04:50 +000011335bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011336 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011337 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011338
11339 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11340 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011341
Chris Lattnerb3d59702005-07-07 20:40:38 +000011342 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011343 // Do a depth-first traversal of the function, populate the worklist with
11344 // the reachable instructions. Ignore blocks that are not reachable. Keep
11345 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011346 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011347 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011348
Chris Lattnerb3d59702005-07-07 20:40:38 +000011349 // Do a quick scan over the function. If we find any blocks that are
11350 // unreachable, remove any instructions inside of them. This prevents
11351 // the instcombine code from having to deal with some bad special cases.
11352 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11353 if (!Visited.count(BB)) {
11354 Instruction *Term = BB->getTerminator();
11355 while (Term != BB->begin()) { // Remove instrs bottom-up
11356 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011357
Bill Wendlingb7427032006-11-26 09:46:52 +000011358 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011359 ++NumDeadInst;
11360
11361 if (!I->use_empty())
11362 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11363 I->eraseFromParent();
11364 }
11365 }
11366 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011367
Chris Lattnerdbab3862007-03-02 21:28:56 +000011368 while (!Worklist.empty()) {
11369 Instruction *I = RemoveOneFromWorkList();
11370 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011371
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011372 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011373 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011374 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011375 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011376 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011377 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011378
Bill Wendlingb7427032006-11-26 09:46:52 +000011379 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011380
11381 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011382 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011383 continue;
11384 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011385
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011386 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011387 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011388 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011389
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011390 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011391 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011392 ReplaceInstUsesWith(*I, C);
11393
Chris Lattner62b14df2002-09-02 04:59:56 +000011394 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011395 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011396 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011397 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011398 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011399
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000011400 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11401 // See if we can constant fold its operands.
11402 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11403 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11404 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11405 i->set(NewC);
11406 }
11407 }
11408 }
11409
Chris Lattnerea1c4542004-12-08 23:43:58 +000011410 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011411 // FIXME: Remove GetResultInst test when first class support for aggregates
11412 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011413 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011414 BasicBlock *BB = I->getParent();
11415 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11416 if (UserParent != BB) {
11417 bool UserIsSuccessor = false;
11418 // See if the user is one of our successors.
11419 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11420 if (*SI == UserParent) {
11421 UserIsSuccessor = true;
11422 break;
11423 }
11424
11425 // If the user is one of our immediate successors, and if that successor
11426 // only has us as a predecessors (we'd have to split the critical edge
11427 // otherwise), we can keep going.
11428 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11429 next(pred_begin(UserParent)) == pred_end(UserParent))
11430 // Okay, the CFG is simple enough, try to sink this instruction.
11431 Changed |= TryToSinkInstruction(I, UserParent);
11432 }
11433 }
11434
Chris Lattner8a2a3112001-12-14 16:52:21 +000011435 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011436#ifndef NDEBUG
11437 std::string OrigI;
11438#endif
11439 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011440 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011441 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011442 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011443 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011444 DOUT << "IC: Old = " << *I
11445 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011446
Chris Lattnerf523d062004-06-09 05:08:07 +000011447 // Everything uses the new instruction now.
11448 I->replaceAllUsesWith(Result);
11449
11450 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011451 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011452 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011453
Chris Lattner6934a042007-02-11 01:23:03 +000011454 // Move the name to the new instruction first.
11455 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011456
11457 // Insert the new instruction into the basic block...
11458 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011459 BasicBlock::iterator InsertPos = I;
11460
11461 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11462 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11463 ++InsertPos;
11464
11465 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011466
Chris Lattner00d51312004-05-01 23:27:23 +000011467 // Make sure that we reprocess all operands now that we reduced their
11468 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011469 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011470
Chris Lattnerf523d062004-06-09 05:08:07 +000011471 // Instructions can end up on the worklist more than once. Make sure
11472 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011473 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011474
11475 // Erase the old instruction.
11476 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011477 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011478#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011479 DOUT << "IC: Mod = " << OrigI
11480 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011481#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011482
Chris Lattner90ac28c2002-08-02 19:29:35 +000011483 // If the instruction was modified, it's possible that it is now dead.
11484 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011485 if (isInstructionTriviallyDead(I)) {
11486 // Make sure we process all operands now that we are reducing their
11487 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011488 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011489
Chris Lattner00d51312004-05-01 23:27:23 +000011490 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011491 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011492 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011493 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011494 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011495 AddToWorkList(I);
11496 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011497 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011498 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011499 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011500 }
11501 }
11502
Chris Lattnerec9c3582007-03-03 02:04:50 +000011503 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011504
11505 // Do an explicit clear, this shrinks the map if needed.
11506 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011507 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011508}
11509
Chris Lattnerec9c3582007-03-03 02:04:50 +000011510
11511bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011512 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11513
Chris Lattnerec9c3582007-03-03 02:04:50 +000011514 bool EverMadeChange = false;
11515
11516 // Iterate while there is work to do.
11517 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011518 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011519 EverMadeChange = true;
11520 return EverMadeChange;
11521}
11522
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011523FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011524 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011525}
Brian Gaeked0fde302003-11-11 22:41:34 +000011526