blob: c04df4a749b560fc8afaae021f5359a787390889 [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) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*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
Gabor Greif177dd3f2008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*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.
Gabor Greif177dd3f2008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000144 }
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
Gabor Greif177dd3f2008-06-12 21:37:33 +00004588 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4589 ++i, ++GTI) {
4590 Value *Op = *i;
Duncan Sands514ab342007-11-01 20:53:16 +00004591 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004592 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4593 if (OpC->isZero()) continue;
4594
4595 // Handle a struct index, which adds its field offset to the pointer.
4596 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4597 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4598
4599 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4600 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004601 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004602 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004603 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004604 ConstantInt::get(IntPtrTy, Size),
4605 GEP->getName()+".offs"), I);
4606 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004607 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004608
4609 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4610 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4611 Scale = ConstantExpr::getMul(OC, Scale);
4612 if (Constant *RC = dyn_cast<Constant>(Result))
4613 Result = ConstantExpr::getAdd(RC, Scale);
4614 else {
4615 // Emit an add instruction.
4616 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004617 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004618 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004619 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004620 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004621 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004622 // Convert to correct type.
4623 if (Op->getType() != IntPtrTy) {
4624 if (Constant *OpC = dyn_cast<Constant>(Op))
4625 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4626 else
4627 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4628 Op->getName()+".c"), I);
4629 }
4630 if (Size != 1) {
4631 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4632 if (Constant *OpC = dyn_cast<Constant>(Op))
4633 Op = ConstantExpr::getMul(OpC, Scale);
4634 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004635 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004636 GEP->getName()+".idx"), I);
4637 }
4638
4639 // Emit an add instruction.
4640 if (isa<Constant>(Op) && isa<Constant>(Result))
4641 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4642 cast<Constant>(Result));
4643 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004644 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004645 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004646 }
4647 return Result;
4648}
4649
Chris Lattner10c0d912008-04-22 02:53:33 +00004650
4651/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4652/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4653/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4654/// complex, and scales are involved. The above expression would also be legal
4655/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4656/// later form is less amenable to optimization though, and we are allowed to
4657/// generate the first by knowing that pointer arithmetic doesn't overflow.
4658///
4659/// If we can't emit an optimized form for this expression, this returns null.
4660///
4661static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4662 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00004663 TargetData &TD = IC.getTargetData();
4664 gep_type_iterator GTI = gep_type_begin(GEP);
4665
4666 // Check to see if this gep only has a single variable index. If so, and if
4667 // any constant indices are a multiple of its scale, then we can compute this
4668 // in terms of the scale of the variable index. For example, if the GEP
4669 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4670 // because the expression will cross zero at the same point.
4671 unsigned i, e = GEP->getNumOperands();
4672 int64_t Offset = 0;
4673 for (i = 1; i != e; ++i, ++GTI) {
4674 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4675 // Compute the aggregate offset of constant indices.
4676 if (CI->isZero()) continue;
4677
4678 // Handle a struct index, which adds its field offset to the pointer.
4679 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4680 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4681 } else {
4682 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4683 Offset += Size*CI->getSExtValue();
4684 }
4685 } else {
4686 // Found our variable index.
4687 break;
4688 }
4689 }
4690
4691 // If there are no variable indices, we must have a constant offset, just
4692 // evaluate it the general way.
4693 if (i == e) return 0;
4694
4695 Value *VariableIdx = GEP->getOperand(i);
4696 // Determine the scale factor of the variable element. For example, this is
4697 // 4 if the variable index is into an array of i32.
4698 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4699
4700 // Verify that there are no other variable indices. If so, emit the hard way.
4701 for (++i, ++GTI; i != e; ++i, ++GTI) {
4702 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4703 if (!CI) return 0;
4704
4705 // Compute the aggregate offset of constant indices.
4706 if (CI->isZero()) continue;
4707
4708 // Handle a struct index, which adds its field offset to the pointer.
4709 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4710 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4711 } else {
4712 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4713 Offset += Size*CI->getSExtValue();
4714 }
4715 }
4716
4717 // Okay, we know we have a single variable index, which must be a
4718 // pointer/array/vector index. If there is no offset, life is simple, return
4719 // the index.
4720 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4721 if (Offset == 0) {
4722 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4723 // we don't need to bother extending: the extension won't affect where the
4724 // computation crosses zero.
4725 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4726 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4727 VariableIdx->getNameStart(), &I);
4728 return VariableIdx;
4729 }
4730
4731 // Otherwise, there is an index. The computation we will do will be modulo
4732 // the pointer size, so get it.
4733 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4734
4735 Offset &= PtrSizeMask;
4736 VariableScale &= PtrSizeMask;
4737
4738 // To do this transformation, any constant index must be a multiple of the
4739 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4740 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4741 // multiple of the variable scale.
4742 int64_t NewOffs = Offset / (int64_t)VariableScale;
4743 if (Offset != NewOffs*(int64_t)VariableScale)
4744 return 0;
4745
4746 // Okay, we can do this evaluation. Start by converting the index to intptr.
4747 const Type *IntPtrTy = TD.getIntPtrType();
4748 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004749 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00004750 true /*SExt*/,
4751 VariableIdx->getNameStart(), &I);
4752 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004753 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00004754}
4755
4756
Reid Spencere4d87aa2006-12-23 06:05:41 +00004757/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004758/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004759Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4760 ICmpInst::Predicate Cond,
4761 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004762 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004763
Chris Lattner10c0d912008-04-22 02:53:33 +00004764 // Look through bitcasts.
4765 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4766 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004767
Chris Lattner574da9b2005-01-13 20:14:25 +00004768 Value *PtrBase = GEPLHS->getOperand(0);
4769 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004770 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00004771 // This transformation (ignoring the base and scales) is valid because we
4772 // know pointers can't overflow. See if we can output an optimized form.
4773 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4774
4775 // If not, synthesize the offset the hard way.
4776 if (Offset == 0)
4777 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00004778 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4779 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004780 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004781 // If the base pointers are different, but the indices are the same, just
4782 // compare the base pointer.
4783 if (PtrBase != GEPRHS->getOperand(0)) {
4784 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004785 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004786 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004787 if (IndicesTheSame)
4788 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4789 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4790 IndicesTheSame = false;
4791 break;
4792 }
4793
4794 // If all indices are the same, just compare the base pointers.
4795 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004796 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4797 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004798
4799 // Otherwise, the base pointers are different and the indices are
4800 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004801 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004802 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004803
Chris Lattnere9d782b2005-01-13 22:25:21 +00004804 // If one of the GEPs has all zero indices, recurse.
4805 bool AllZeros = true;
4806 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4807 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4808 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4809 AllZeros = false;
4810 break;
4811 }
4812 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004813 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4814 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004815
4816 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004817 AllZeros = true;
4818 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4819 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4820 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4821 AllZeros = false;
4822 break;
4823 }
4824 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004825 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004826
Chris Lattner4401c9c2005-01-14 00:20:05 +00004827 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4828 // If the GEPs only differ by one index, compare it.
4829 unsigned NumDifferences = 0; // Keep track of # differences.
4830 unsigned DiffOperand = 0; // The operand that differs.
4831 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4832 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004833 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4834 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004835 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004836 NumDifferences = 2;
4837 break;
4838 } else {
4839 if (NumDifferences++) break;
4840 DiffOperand = i;
4841 }
4842 }
4843
4844 if (NumDifferences == 0) // SAME GEP?
4845 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004846 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00004847 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00004848
Chris Lattner4401c9c2005-01-14 00:20:05 +00004849 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004850 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4851 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004852 // Make sure we do a signed comparison here.
4853 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004854 }
4855 }
4856
Reid Spencere4d87aa2006-12-23 06:05:41 +00004857 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004858 // the result to fold to a constant!
4859 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4860 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4861 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4862 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4863 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004864 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004865 }
4866 }
4867 return 0;
4868}
4869
Chris Lattnera5406232008-05-19 20:18:56 +00004870/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4871///
4872Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4873 Instruction *LHSI,
4874 Constant *RHSC) {
4875 if (!isa<ConstantFP>(RHSC)) return 0;
4876 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4877
4878 // Get the width of the mantissa. We don't want to hack on conversions that
4879 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00004880 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00004881 if (MantissaWidth == -1) return 0; // Unknown.
4882
4883 // Check to see that the input is converted from an integer type that is small
4884 // enough that preserves all bits. TODO: check here for "known" sign bits.
4885 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4886 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4887
4888 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4889 if (isa<UIToFPInst>(LHSI))
4890 ++InputSize;
4891
4892 // If the conversion would lose info, don't hack on this.
4893 if ((int)InputSize > MantissaWidth)
4894 return 0;
4895
4896 // Otherwise, we can potentially simplify the comparison. We know that it
4897 // will always come through as an integer value and we know the constant is
4898 // not a NAN (it would have been previously simplified).
4899 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4900
4901 ICmpInst::Predicate Pred;
4902 switch (I.getPredicate()) {
4903 default: assert(0 && "Unexpected predicate!");
4904 case FCmpInst::FCMP_UEQ:
4905 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4906 case FCmpInst::FCMP_UGT:
4907 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4908 case FCmpInst::FCMP_UGE:
4909 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4910 case FCmpInst::FCMP_ULT:
4911 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4912 case FCmpInst::FCMP_ULE:
4913 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4914 case FCmpInst::FCMP_UNE:
4915 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4916 case FCmpInst::FCMP_ORD:
4917 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4918 case FCmpInst::FCMP_UNO:
4919 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4920 }
4921
4922 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4923
4924 // Now we know that the APFloat is a normal number, zero or inf.
4925
Chris Lattner85162782008-05-20 03:50:52 +00004926 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00004927 // comparing an i8 to 300.0.
4928 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4929
4930 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4931 // and large values.
4932 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4933 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4934 APFloat::rmNearestTiesToEven);
4935 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004936 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4937 Pred == ICmpInst::ICMP_SLE)
Chris Lattnera5406232008-05-19 20:18:56 +00004938 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4939 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4940 }
4941
4942 // See if the RHS value is < SignedMin.
4943 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4944 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4945 APFloat::rmNearestTiesToEven);
4946 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004947 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4948 Pred == ICmpInst::ICMP_SGE)
Chris Lattnera5406232008-05-19 20:18:56 +00004949 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4950 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4951 }
4952
4953 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4954 // it may still be fractional. See if it is fractional by casting the FP
4955 // value to the integer value and back, checking for equality. Don't do this
4956 // for zero, because -0.0 is not fractional.
4957 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4958 if (!RHS.isZero() &&
4959 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4960 // If we had a comparison against a fractional value, we have to adjust
4961 // the compare predicate and sometimes the value. RHSC is rounded towards
4962 // zero at this point.
4963 switch (Pred) {
4964 default: assert(0 && "Unexpected integer comparison!");
4965 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
4966 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4967 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
4968 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4969 case ICmpInst::ICMP_SLE:
4970 // (float)int <= 4.4 --> int <= 4
4971 // (float)int <= -4.4 --> int < -4
4972 if (RHS.isNegative())
4973 Pred = ICmpInst::ICMP_SLT;
4974 break;
4975 case ICmpInst::ICMP_SLT:
4976 // (float)int < -4.4 --> int < -4
4977 // (float)int < 4.4 --> int <= 4
4978 if (!RHS.isNegative())
4979 Pred = ICmpInst::ICMP_SLE;
4980 break;
4981 case ICmpInst::ICMP_SGT:
4982 // (float)int > 4.4 --> int > 4
4983 // (float)int > -4.4 --> int >= -4
4984 if (RHS.isNegative())
4985 Pred = ICmpInst::ICMP_SGE;
4986 break;
4987 case ICmpInst::ICMP_SGE:
4988 // (float)int >= -4.4 --> int >= -4
4989 // (float)int >= 4.4 --> int > 4
4990 if (!RHS.isNegative())
4991 Pred = ICmpInst::ICMP_SGT;
4992 break;
4993 }
4994 }
4995
4996 // Lower this FP comparison into an appropriate integer version of the
4997 // comparison.
4998 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4999}
5000
Reid Spencere4d87aa2006-12-23 06:05:41 +00005001Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5002 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005003 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005004
Chris Lattner58e97462007-01-14 19:42:17 +00005005 // Fold trivial predicates.
5006 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5007 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5008 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5009 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5010
5011 // Simplify 'fcmp pred X, X'
5012 if (Op0 == Op1) {
5013 switch (I.getPredicate()) {
5014 default: assert(0 && "Unknown predicate!");
5015 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5016 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5017 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5018 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5019 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5020 case FCmpInst::FCMP_OLT: // True if ordered and less than
5021 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5022 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5023
5024 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5025 case FCmpInst::FCMP_ULT: // True if unordered or less than
5026 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5027 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5028 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5029 I.setPredicate(FCmpInst::FCMP_UNO);
5030 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5031 return &I;
5032
5033 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5034 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5035 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5036 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5037 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5038 I.setPredicate(FCmpInst::FCMP_ORD);
5039 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5040 return &I;
5041 }
5042 }
5043
Reid Spencere4d87aa2006-12-23 06:05:41 +00005044 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005045 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005046
Reid Spencere4d87aa2006-12-23 06:05:41 +00005047 // Handle fcmp with constant RHS
5048 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005049 // If the constant is a nan, see if we can fold the comparison based on it.
5050 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5051 if (CFP->getValueAPF().isNaN()) {
5052 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5053 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005054 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5055 "Comparison must be either ordered or unordered!");
5056 // True if unordered.
5057 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005058 }
5059 }
5060
Reid Spencere4d87aa2006-12-23 06:05:41 +00005061 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5062 switch (LHSI->getOpcode()) {
5063 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005064 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5065 // block. If in the same block, we're encouraging jump threading. If
5066 // not, we are just pessimizing the code by making an i1 phi.
5067 if (LHSI->getParent() == I.getParent())
5068 if (Instruction *NV = FoldOpIntoPhi(I))
5069 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005070 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005071 case Instruction::SIToFP:
5072 case Instruction::UIToFP:
5073 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5074 return NV;
5075 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005076 case Instruction::Select:
5077 // If either operand of the select is a constant, we can fold the
5078 // comparison into the select arms, which will cause one to be
5079 // constant folded and the select turned into a bitwise or.
5080 Value *Op1 = 0, *Op2 = 0;
5081 if (LHSI->hasOneUse()) {
5082 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5083 // Fold the known value into the constant operand.
5084 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5085 // Insert a new FCmp of the other select operand.
5086 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5087 LHSI->getOperand(2), RHSC,
5088 I.getName()), I);
5089 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5090 // Fold the known value into the constant operand.
5091 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5092 // Insert a new FCmp of the other select operand.
5093 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5094 LHSI->getOperand(1), RHSC,
5095 I.getName()), I);
5096 }
5097 }
5098
5099 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005100 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005101 break;
5102 }
5103 }
5104
5105 return Changed ? &I : 0;
5106}
5107
5108Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5109 bool Changed = SimplifyCompare(I);
5110 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5111 const Type *Ty = Op0->getType();
5112
5113 // icmp X, X
5114 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005115 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005116 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005117
5118 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005119 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005120
Reid Spencere4d87aa2006-12-23 06:05:41 +00005121 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005122 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005123 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5124 isa<ConstantPointerNull>(Op0)) &&
5125 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005126 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005127 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005128 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005129
Reid Spencere4d87aa2006-12-23 06:05:41 +00005130 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005131 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005132 switch (I.getPredicate()) {
5133 default: assert(0 && "Invalid icmp instruction!");
5134 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005135 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005136 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005137 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005138 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005139 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005140 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005141
Reid Spencere4d87aa2006-12-23 06:05:41 +00005142 case ICmpInst::ICMP_UGT:
5143 case ICmpInst::ICMP_SGT:
5144 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005145 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005146 case ICmpInst::ICMP_ULT:
5147 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005148 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005149 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005150 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005151 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005152 case ICmpInst::ICMP_UGE:
5153 case ICmpInst::ICMP_SGE:
5154 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005155 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005156 case ICmpInst::ICMP_ULE:
5157 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005158 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005159 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005160 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005161 }
5162 }
Chris Lattner8b170942002-08-09 23:47:40 +00005163 }
5164
Chris Lattner2be51ae2004-06-09 04:24:29 +00005165 // See if we are doing a comparison between a constant and an instruction that
5166 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005167 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005168 Value *A, *B;
5169
Chris Lattnerb6566012008-01-05 01:18:20 +00005170 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5171 if (I.isEquality() && CI->isNullValue() &&
5172 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5173 // (icmp cond A B) if cond is equality
5174 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005175 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005176
Reid Spencere4d87aa2006-12-23 06:05:41 +00005177 switch (I.getPredicate()) {
5178 default: break;
5179 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5180 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005181 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005182 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5183 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5184 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5185 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005186 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5187 if (CI->isMinValue(true))
5188 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5189 ConstantInt::getAllOnesValue(Op0->getType()));
5190
Reid Spencere4d87aa2006-12-23 06:05:41 +00005191 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005192
Reid Spencere4d87aa2006-12-23 06:05:41 +00005193 case ICmpInst::ICMP_SLT:
5194 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005195 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005196 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5197 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5198 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5199 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5200 break;
5201
5202 case ICmpInst::ICMP_UGT:
5203 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005204 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005205 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5206 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5207 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5208 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005209
5210 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5211 if (CI->isMaxValue(true))
5212 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5213 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005214 break;
5215
5216 case ICmpInst::ICMP_SGT:
5217 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005218 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005219 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5220 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5221 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5222 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5223 break;
5224
5225 case ICmpInst::ICMP_ULE:
5226 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005227 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005228 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5229 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5230 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5231 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5232 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005233
Reid Spencere4d87aa2006-12-23 06:05:41 +00005234 case ICmpInst::ICMP_SLE:
5235 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005236 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005237 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5238 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5239 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5240 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5241 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005242
Reid Spencere4d87aa2006-12-23 06:05:41 +00005243 case ICmpInst::ICMP_UGE:
5244 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005245 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005246 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5247 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5248 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5249 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5250 break;
5251
5252 case ICmpInst::ICMP_SGE:
5253 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005254 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005255 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5256 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5257 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5258 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5259 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005260 }
5261
Reid Spencere4d87aa2006-12-23 06:05:41 +00005262 // If we still have a icmp le or icmp ge instruction, turn it into the
5263 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005264 // already been handled above, this requires little checking.
5265 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005266 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005267 default: break;
5268 case ICmpInst::ICMP_ULE:
5269 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5270 case ICmpInst::ICMP_SLE:
5271 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5272 case ICmpInst::ICMP_UGE:
5273 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5274 case ICmpInst::ICMP_SGE:
5275 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005276 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005277
5278 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005279 // in the input. If this comparison is a normal comparison, it demands all
5280 // bits, if it is a sign bit comparison, it only demands the sign bit.
5281
5282 bool UnusedBit;
5283 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5284
Reid Spencer0460fb32007-03-22 20:36:03 +00005285 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5286 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005287 if (SimplifyDemandedBits(Op0,
5288 isSignBit ? APInt::getSignBit(BitWidth)
5289 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005290 KnownZero, KnownOne, 0))
5291 return &I;
5292
5293 // Given the known and unknown bits, compute a range that the LHS could be
5294 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005295 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005296 // Compute the Min, Max and RHS values based on the known bits. For the
5297 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005298 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5299 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005300 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005301 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5302 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005303 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005304 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5305 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005306 }
5307 switch (I.getPredicate()) { // LE/GE have been folded already.
5308 default: assert(0 && "Unknown icmp opcode!");
5309 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005310 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005311 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005312 break;
5313 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005314 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005315 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005316 break;
5317 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005318 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005319 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005320 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005321 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005322 break;
5323 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005324 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005325 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005326 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005327 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005328 break;
5329 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005330 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005331 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005332 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005333 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005334 break;
5335 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005336 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005337 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005338 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005339 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005340 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005341 }
5342 }
5343
Reid Spencere4d87aa2006-12-23 06:05:41 +00005344 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005345 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005346 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005347 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005348 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5349 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005350 }
5351
Chris Lattner01deb9d2007-04-03 17:43:25 +00005352 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005353 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5354 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5355 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005356 case Instruction::GetElementPtr:
5357 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005358 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005359 bool isAllZeros = true;
5360 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5361 if (!isa<Constant>(LHSI->getOperand(i)) ||
5362 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5363 isAllZeros = false;
5364 break;
5365 }
5366 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005367 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005368 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5369 }
5370 break;
5371
Chris Lattner6970b662005-04-23 15:31:55 +00005372 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005373 // Only fold icmp into the PHI if the phi and fcmp are in the same
5374 // block. If in the same block, we're encouraging jump threading. If
5375 // not, we are just pessimizing the code by making an i1 phi.
5376 if (LHSI->getParent() == I.getParent())
5377 if (Instruction *NV = FoldOpIntoPhi(I))
5378 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005379 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005380 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005381 // If either operand of the select is a constant, we can fold the
5382 // comparison into the select arms, which will cause one to be
5383 // constant folded and the select turned into a bitwise or.
5384 Value *Op1 = 0, *Op2 = 0;
5385 if (LHSI->hasOneUse()) {
5386 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5387 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005388 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5389 // Insert a new ICmp of the other select operand.
5390 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5391 LHSI->getOperand(2), RHSC,
5392 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005393 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5394 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005395 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5396 // Insert a new ICmp of the other select operand.
5397 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5398 LHSI->getOperand(1), RHSC,
5399 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005400 }
5401 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005402
Chris Lattner6970b662005-04-23 15:31:55 +00005403 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005404 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005405 break;
5406 }
Chris Lattner4802d902007-04-06 18:57:34 +00005407 case Instruction::Malloc:
5408 // If we have (malloc != null), and if the malloc has a single use, we
5409 // can assume it is successful and remove the malloc.
5410 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5411 AddToWorkList(LHSI);
5412 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005413 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005414 }
5415 break;
5416 }
Chris Lattner6970b662005-04-23 15:31:55 +00005417 }
5418
Reid Spencere4d87aa2006-12-23 06:05:41 +00005419 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005420 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005421 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005422 return NI;
5423 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005424 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5425 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005426 return NI;
5427
Reid Spencere4d87aa2006-12-23 06:05:41 +00005428 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005429 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5430 // now.
5431 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5432 if (isa<PointerType>(Op0->getType()) &&
5433 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005434 // We keep moving the cast from the left operand over to the right
5435 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005436 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005437
Chris Lattner57d86372007-01-06 01:45:59 +00005438 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5439 // so eliminate it as well.
5440 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5441 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005442
Chris Lattnerde90b762003-11-03 04:25:02 +00005443 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005444 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005445 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005446 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005447 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005448 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005449 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005450 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005451 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005452 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005453 }
Chris Lattner57d86372007-01-06 01:45:59 +00005454 }
5455
5456 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005457 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005458 // This comes up when you have code like
5459 // int X = A < B;
5460 // if (X) ...
5461 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005462 // with a constant or another cast from the same type.
5463 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005464 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005465 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005466 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005467
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005468 // ~x < ~y --> y < x
5469 { Value *A, *B;
5470 if (match(Op0, m_Not(m_Value(A))) &&
5471 match(Op1, m_Not(m_Value(B))))
5472 return new ICmpInst(I.getPredicate(), B, A);
5473 }
5474
Chris Lattner65b72ba2006-09-18 04:22:48 +00005475 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005476 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005477
5478 // -x == -y --> x == y
5479 if (match(Op0, m_Neg(m_Value(A))) &&
5480 match(Op1, m_Neg(m_Value(B))))
5481 return new ICmpInst(I.getPredicate(), A, B);
5482
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005483 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5484 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5485 Value *OtherVal = A == Op1 ? B : A;
5486 return new ICmpInst(I.getPredicate(), OtherVal,
5487 Constant::getNullValue(A->getType()));
5488 }
5489
5490 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5491 // A^c1 == C^c2 --> A == C^(c1^c2)
5492 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5493 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5494 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005495 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005496 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005497 return new ICmpInst(I.getPredicate(), A,
5498 InsertNewInstBefore(Xor, I));
5499 }
5500
5501 // A^B == A^D -> B == D
5502 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5503 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5504 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5505 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5506 }
5507 }
5508
5509 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5510 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005511 // A == (A^B) -> B == 0
5512 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005513 return new ICmpInst(I.getPredicate(), OtherVal,
5514 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005515 }
5516 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005517 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005518 return new ICmpInst(I.getPredicate(), B,
5519 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005520 }
5521 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005522 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005523 return new ICmpInst(I.getPredicate(), B,
5524 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005525 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005526
Chris Lattner9c2328e2006-11-14 06:06:06 +00005527 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5528 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5529 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5530 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5531 Value *X = 0, *Y = 0, *Z = 0;
5532
5533 if (A == C) {
5534 X = B; Y = D; Z = A;
5535 } else if (A == D) {
5536 X = B; Y = C; Z = A;
5537 } else if (B == C) {
5538 X = A; Y = D; Z = B;
5539 } else if (B == D) {
5540 X = A; Y = C; Z = B;
5541 }
5542
5543 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005544 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5545 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005546 I.setOperand(0, Op1);
5547 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5548 return &I;
5549 }
5550 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005551 }
Chris Lattner7e708292002-06-25 16:13:24 +00005552 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005553}
5554
Chris Lattner562ef782007-06-20 23:46:26 +00005555
5556/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5557/// and CmpRHS are both known to be integer constants.
5558Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5559 ConstantInt *DivRHS) {
5560 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5561 const APInt &CmpRHSV = CmpRHS->getValue();
5562
5563 // FIXME: If the operand types don't match the type of the divide
5564 // then don't attempt this transform. The code below doesn't have the
5565 // logic to deal with a signed divide and an unsigned compare (and
5566 // vice versa). This is because (x /s C1) <s C2 produces different
5567 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5568 // (x /u C1) <u C2. Simply casting the operands and result won't
5569 // work. :( The if statement below tests that condition and bails
5570 // if it finds it.
5571 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5572 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5573 return 0;
5574 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005575 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005576
5577 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5578 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5579 // C2 (CI). By solving for X we can turn this into a range check
5580 // instead of computing a divide.
5581 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5582
5583 // Determine if the product overflows by seeing if the product is
5584 // not equal to the divide. Make sure we do the same kind of divide
5585 // as in the LHS instruction that we're folding.
5586 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5587 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5588
5589 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005590 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005591
Chris Lattner1dbfd482007-06-21 18:11:19 +00005592 // Figure out the interval that is being checked. For example, a comparison
5593 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5594 // Compute this interval based on the constants involved and the signedness of
5595 // the compare/divide. This computes a half-open interval, keeping track of
5596 // whether either value in the interval overflows. After analysis each
5597 // overflow variable is set to 0 if it's corresponding bound variable is valid
5598 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5599 int LoOverflow = 0, HiOverflow = 0;
5600 ConstantInt *LoBound = 0, *HiBound = 0;
5601
5602
Chris Lattner562ef782007-06-20 23:46:26 +00005603 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005604 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005605 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005606 HiOverflow = LoOverflow = ProdOV;
5607 if (!HiOverflow)
5608 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005609 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005610 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005611 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005612 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5613 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005614 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005615 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5616 HiOverflow = LoOverflow = ProdOV;
5617 if (!HiOverflow)
5618 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005619 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005620 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005621 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5622 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005623 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005624 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005625 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005626 }
Dan Gohman76491272008-02-13 22:09:18 +00005627 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005628 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005629 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005630 LoBound = AddOne(DivRHS);
5631 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005632 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5633 HiOverflow = 1; // [INTMIN+1, overflow)
5634 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5635 }
Dan Gohman76491272008-02-13 22:09:18 +00005636 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005637 // e.g. X/-5 op 3 --> [-19, -14)
5638 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005639 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005640 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005641 HiBound = AddOne(Prod);
5642 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005643 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005644 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005645 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005646 HiBound = Subtract(Prod, DivRHS);
5647 }
5648
Chris Lattner1dbfd482007-06-21 18:11:19 +00005649 // Dividing by a negative swaps the condition. LT <-> GT
5650 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005651 }
5652
5653 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005654 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005655 default: assert(0 && "Unhandled icmp opcode!");
5656 case ICmpInst::ICMP_EQ:
5657 if (LoOverflow && HiOverflow)
5658 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5659 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005660 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005661 ICmpInst::ICMP_UGE, X, LoBound);
5662 else if (LoOverflow)
5663 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5664 ICmpInst::ICMP_ULT, X, HiBound);
5665 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005666 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005667 case ICmpInst::ICMP_NE:
5668 if (LoOverflow && HiOverflow)
5669 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5670 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005671 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005672 ICmpInst::ICMP_ULT, X, LoBound);
5673 else if (LoOverflow)
5674 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5675 ICmpInst::ICMP_UGE, X, HiBound);
5676 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005677 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005678 case ICmpInst::ICMP_ULT:
5679 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005680 if (LoOverflow == +1) // Low bound is greater than input range.
5681 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5682 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005683 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005684 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005685 case ICmpInst::ICMP_UGT:
5686 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005687 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005688 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005689 else if (HiOverflow == -1) // High bound less than input range.
5690 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5691 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005692 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5693 else
5694 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5695 }
5696}
5697
5698
Chris Lattner01deb9d2007-04-03 17:43:25 +00005699/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5700///
5701Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5702 Instruction *LHSI,
5703 ConstantInt *RHS) {
5704 const APInt &RHSV = RHS->getValue();
5705
5706 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005707 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005708 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5709 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5710 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005711 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5712 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005713 Value *CompareVal = LHSI->getOperand(0);
5714
5715 // If the sign bit of the XorCST is not set, there is no change to
5716 // the operation, just stop using the Xor.
5717 if (!XorCST->getValue().isNegative()) {
5718 ICI.setOperand(0, CompareVal);
5719 AddToWorkList(LHSI);
5720 return &ICI;
5721 }
5722
5723 // Was the old condition true if the operand is positive?
5724 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5725
5726 // If so, the new one isn't.
5727 isTrueIfPositive ^= true;
5728
5729 if (isTrueIfPositive)
5730 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5731 else
5732 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5733 }
5734 }
5735 break;
5736 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5737 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5738 LHSI->getOperand(0)->hasOneUse()) {
5739 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5740
5741 // If the LHS is an AND of a truncating cast, we can widen the
5742 // and/compare to be the input width without changing the value
5743 // produced, eliminating a cast.
5744 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5745 // We can do this transformation if either the AND constant does not
5746 // have its sign bit set or if it is an equality comparison.
5747 // Extending a relational comparison when we're checking the sign
5748 // bit would not work.
5749 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005750 (ICI.isEquality() ||
5751 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005752 uint32_t BitWidth =
5753 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5754 APInt NewCST = AndCST->getValue();
5755 NewCST.zext(BitWidth);
5756 APInt NewCI = RHSV;
5757 NewCI.zext(BitWidth);
5758 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005759 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00005760 ConstantInt::get(NewCST),LHSI->getName());
5761 InsertNewInstBefore(NewAnd, ICI);
5762 return new ICmpInst(ICI.getPredicate(), NewAnd,
5763 ConstantInt::get(NewCI));
5764 }
5765 }
5766
5767 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5768 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5769 // happens a LOT in code produced by the C front-end, for bitfield
5770 // access.
5771 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5772 if (Shift && !Shift->isShift())
5773 Shift = 0;
5774
5775 ConstantInt *ShAmt;
5776 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5777 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5778 const Type *AndTy = AndCST->getType(); // Type of the and.
5779
5780 // We can fold this as long as we can't shift unknown bits
5781 // into the mask. This can only happen with signed shift
5782 // rights, as they sign-extend.
5783 if (ShAmt) {
5784 bool CanFold = Shift->isLogicalShift();
5785 if (!CanFold) {
5786 // To test for the bad case of the signed shr, see if any
5787 // of the bits shifted in could be tested after the mask.
5788 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5789 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5790
5791 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5792 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5793 AndCST->getValue()) == 0)
5794 CanFold = true;
5795 }
5796
5797 if (CanFold) {
5798 Constant *NewCst;
5799 if (Shift->getOpcode() == Instruction::Shl)
5800 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5801 else
5802 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5803
5804 // Check to see if we are shifting out any of the bits being
5805 // compared.
5806 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5807 // If we shifted bits out, the fold is not going to work out.
5808 // As a special case, check to see if this means that the
5809 // result is always true or false now.
5810 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5811 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5812 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5813 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5814 } else {
5815 ICI.setOperand(1, NewCst);
5816 Constant *NewAndCST;
5817 if (Shift->getOpcode() == Instruction::Shl)
5818 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5819 else
5820 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5821 LHSI->setOperand(1, NewAndCST);
5822 LHSI->setOperand(0, Shift->getOperand(0));
5823 AddToWorkList(Shift); // Shift is dead.
5824 AddUsesToWorkList(ICI);
5825 return &ICI;
5826 }
5827 }
5828 }
5829
5830 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5831 // preferable because it allows the C<<Y expression to be hoisted out
5832 // of a loop if Y is invariant and X is not.
5833 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5834 ICI.isEquality() && !Shift->isArithmeticShift() &&
5835 isa<Instruction>(Shift->getOperand(0))) {
5836 // Compute C << Y.
5837 Value *NS;
5838 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005839 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005840 Shift->getOperand(1), "tmp");
5841 } else {
5842 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005843 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005844 Shift->getOperand(1), "tmp");
5845 }
5846 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5847
5848 // Compute X & (C << Y).
5849 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005850 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00005851 InsertNewInstBefore(NewAnd, ICI);
5852
5853 ICI.setOperand(0, NewAnd);
5854 return &ICI;
5855 }
5856 }
5857 break;
5858
Chris Lattnera0141b92007-07-15 20:42:37 +00005859 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5860 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5861 if (!ShAmt) break;
5862
5863 uint32_t TypeBits = RHSV.getBitWidth();
5864
5865 // Check that the shift amount is in range. If not, don't perform
5866 // undefined shifts. When the shift is visited it will be
5867 // simplified.
5868 if (ShAmt->uge(TypeBits))
5869 break;
5870
5871 if (ICI.isEquality()) {
5872 // If we are comparing against bits always shifted out, the
5873 // comparison cannot succeed.
5874 Constant *Comp =
5875 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5876 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5877 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5878 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5879 return ReplaceInstUsesWith(ICI, Cst);
5880 }
5881
5882 if (LHSI->hasOneUse()) {
5883 // Otherwise strength reduce the shift into an and.
5884 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5885 Constant *Mask =
5886 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005887
Chris Lattnera0141b92007-07-15 20:42:37 +00005888 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005889 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005890 Mask, LHSI->getName()+".mask");
5891 Value *And = InsertNewInstBefore(AndI, ICI);
5892 return new ICmpInst(ICI.getPredicate(), And,
5893 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005894 }
5895 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005896
5897 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5898 bool TrueIfSigned = false;
5899 if (LHSI->hasOneUse() &&
5900 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5901 // (X << 31) <s 0 --> (X&1) != 0
5902 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5903 (TypeBits-ShAmt->getZExtValue()-1));
5904 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005905 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005906 Mask, LHSI->getName()+".mask");
5907 Value *And = InsertNewInstBefore(AndI, ICI);
5908
5909 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5910 And, Constant::getNullValue(And->getType()));
5911 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005912 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005913 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005914
5915 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005916 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005917 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005918 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005919 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005920
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005921 // Check that the shift amount is in range. If not, don't perform
5922 // undefined shifts. When the shift is visited it will be
5923 // simplified.
5924 uint32_t TypeBits = RHSV.getBitWidth();
5925 if (ShAmt->uge(TypeBits))
5926 break;
5927
5928 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005929
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005930 // If we are comparing against bits always shifted out, the
5931 // comparison cannot succeed.
5932 APInt Comp = RHSV << ShAmtVal;
5933 if (LHSI->getOpcode() == Instruction::LShr)
5934 Comp = Comp.lshr(ShAmtVal);
5935 else
5936 Comp = Comp.ashr(ShAmtVal);
5937
5938 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5939 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5940 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5941 return ReplaceInstUsesWith(ICI, Cst);
5942 }
5943
5944 // Otherwise, check to see if the bits shifted out are known to be zero.
5945 // If so, we can compare against the unshifted value:
5946 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00005947 if (LHSI->hasOneUse() &&
5948 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005949 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5950 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5951 ConstantExpr::getShl(RHS, ShAmt));
5952 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005953
Evan Chengf30752c2008-04-23 00:38:06 +00005954 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005955 // Otherwise strength reduce the shift into an and.
5956 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5957 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00005958
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005959 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005960 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005961 Mask, LHSI->getName()+".mask");
5962 Value *And = InsertNewInstBefore(AndI, ICI);
5963 return new ICmpInst(ICI.getPredicate(), And,
5964 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005965 }
5966 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005967 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005968
5969 case Instruction::SDiv:
5970 case Instruction::UDiv:
5971 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5972 // Fold this div into the comparison, producing a range check.
5973 // Determine, based on the divide type, what the range is being
5974 // checked. If there is an overflow on the low or high side, remember
5975 // it, otherwise compute the range [low, hi) bounding the new value.
5976 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005977 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5978 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5979 DivRHS))
5980 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005981 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005982
5983 case Instruction::Add:
5984 // Fold: icmp pred (add, X, C1), C2
5985
5986 if (!ICI.isEquality()) {
5987 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5988 if (!LHSC) break;
5989 const APInt &LHSV = LHSC->getValue();
5990
5991 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5992 .subtract(LHSV);
5993
5994 if (ICI.isSignedPredicate()) {
5995 if (CR.getLower().isSignBit()) {
5996 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5997 ConstantInt::get(CR.getUpper()));
5998 } else if (CR.getUpper().isSignBit()) {
5999 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6000 ConstantInt::get(CR.getLower()));
6001 }
6002 } else {
6003 if (CR.getLower().isMinValue()) {
6004 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6005 ConstantInt::get(CR.getUpper()));
6006 } else if (CR.getUpper().isMinValue()) {
6007 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6008 ConstantInt::get(CR.getLower()));
6009 }
6010 }
6011 }
6012 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006013 }
6014
6015 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6016 if (ICI.isEquality()) {
6017 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6018
6019 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6020 // the second operand is a constant, simplify a bit.
6021 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6022 switch (BO->getOpcode()) {
6023 case Instruction::SRem:
6024 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6025 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6026 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6027 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6028 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006029 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006030 BO->getName());
6031 InsertNewInstBefore(NewRem, ICI);
6032 return new ICmpInst(ICI.getPredicate(), NewRem,
6033 Constant::getNullValue(BO->getType()));
6034 }
6035 }
6036 break;
6037 case Instruction::Add:
6038 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6039 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6040 if (BO->hasOneUse())
6041 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6042 Subtract(RHS, BOp1C));
6043 } else if (RHSV == 0) {
6044 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6045 // efficiently invertible, or if the add has just this one use.
6046 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6047
6048 if (Value *NegVal = dyn_castNegVal(BOp1))
6049 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6050 else if (Value *NegVal = dyn_castNegVal(BOp0))
6051 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6052 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006053 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006054 InsertNewInstBefore(Neg, ICI);
6055 Neg->takeName(BO);
6056 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6057 }
6058 }
6059 break;
6060 case Instruction::Xor:
6061 // For the xor case, we can xor two constants together, eliminating
6062 // the explicit xor.
6063 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6064 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6065 ConstantExpr::getXor(RHS, BOC));
6066
6067 // FALLTHROUGH
6068 case Instruction::Sub:
6069 // Replace (([sub|xor] A, B) != 0) with (A != B)
6070 if (RHSV == 0)
6071 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6072 BO->getOperand(1));
6073 break;
6074
6075 case Instruction::Or:
6076 // If bits are being or'd in that are not present in the constant we
6077 // are comparing against, then the comparison could never succeed!
6078 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6079 Constant *NotCI = ConstantExpr::getNot(RHS);
6080 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6081 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6082 isICMP_NE));
6083 }
6084 break;
6085
6086 case Instruction::And:
6087 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6088 // If bits are being compared against that are and'd out, then the
6089 // comparison can never succeed!
6090 if ((RHSV & ~BOC->getValue()) != 0)
6091 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6092 isICMP_NE));
6093
6094 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6095 if (RHS == BOC && RHSV.isPowerOf2())
6096 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6097 ICmpInst::ICMP_NE, LHSI,
6098 Constant::getNullValue(RHS->getType()));
6099
6100 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006101 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006102 Value *X = BO->getOperand(0);
6103 Constant *Zero = Constant::getNullValue(X->getType());
6104 ICmpInst::Predicate pred = isICMP_NE ?
6105 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6106 return new ICmpInst(pred, X, Zero);
6107 }
6108
6109 // ((X & ~7) == 0) --> X < 8
6110 if (RHSV == 0 && isHighOnes(BOC)) {
6111 Value *X = BO->getOperand(0);
6112 Constant *NegX = ConstantExpr::getNeg(BOC);
6113 ICmpInst::Predicate pred = isICMP_NE ?
6114 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6115 return new ICmpInst(pred, X, NegX);
6116 }
6117 }
6118 default: break;
6119 }
6120 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6121 // Handle icmp {eq|ne} <intrinsic>, intcst.
6122 if (II->getIntrinsicID() == Intrinsic::bswap) {
6123 AddToWorkList(II);
6124 ICI.setOperand(0, II->getOperand(1));
6125 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6126 return &ICI;
6127 }
6128 }
6129 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006130 // If the LHS is a cast from an integral value of the same size,
6131 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006132 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6133 Value *CastOp = Cast->getOperand(0);
6134 const Type *SrcTy = CastOp->getType();
6135 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6136 if (SrcTy->isInteger() &&
6137 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6138 // If this is an unsigned comparison, try to make the comparison use
6139 // smaller constant values.
6140 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6141 // X u< 128 => X s> -1
6142 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6143 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6144 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6145 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6146 // X u> 127 => X s< 0
6147 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6148 Constant::getNullValue(SrcTy));
6149 }
6150 }
6151 }
6152 }
6153 return 0;
6154}
6155
6156/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6157/// We only handle extending casts so far.
6158///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006159Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6160 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006161 Value *LHSCIOp = LHSCI->getOperand(0);
6162 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006163 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006164 Value *RHSCIOp;
6165
Chris Lattner8c756c12007-05-05 22:41:33 +00006166 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6167 // integer type is the same size as the pointer type.
6168 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6169 getTargetData().getPointerSizeInBits() ==
6170 cast<IntegerType>(DestTy)->getBitWidth()) {
6171 Value *RHSOp = 0;
6172 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006173 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006174 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6175 RHSOp = RHSC->getOperand(0);
6176 // If the pointer types don't match, insert a bitcast.
6177 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006178 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006179 }
6180
6181 if (RHSOp)
6182 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6183 }
6184
6185 // The code below only handles extension cast instructions, so far.
6186 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006187 if (LHSCI->getOpcode() != Instruction::ZExt &&
6188 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006189 return 0;
6190
Reid Spencere4d87aa2006-12-23 06:05:41 +00006191 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6192 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006193
Reid Spencere4d87aa2006-12-23 06:05:41 +00006194 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006195 // Not an extension from the same type?
6196 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006197 if (RHSCIOp->getType() != LHSCIOp->getType())
6198 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006199
Nick Lewycky4189a532008-01-28 03:48:02 +00006200 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006201 // and the other is a zext), then we can't handle this.
6202 if (CI->getOpcode() != LHSCI->getOpcode())
6203 return 0;
6204
Nick Lewycky4189a532008-01-28 03:48:02 +00006205 // Deal with equality cases early.
6206 if (ICI.isEquality())
6207 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6208
6209 // A signed comparison of sign extended values simplifies into a
6210 // signed comparison.
6211 if (isSignedCmp && isSignedExt)
6212 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6213
6214 // The other three cases all fold into an unsigned comparison.
6215 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006216 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006217
Reid Spencere4d87aa2006-12-23 06:05:41 +00006218 // If we aren't dealing with a constant on the RHS, exit early
6219 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6220 if (!CI)
6221 return 0;
6222
6223 // Compute the constant that would happen if we truncated to SrcTy then
6224 // reextended to DestTy.
6225 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6226 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6227
6228 // If the re-extended constant didn't change...
6229 if (Res2 == CI) {
6230 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6231 // For example, we might have:
6232 // %A = sext short %X to uint
6233 // %B = icmp ugt uint %A, 1330
6234 // It is incorrect to transform this into
6235 // %B = icmp ugt short %X, 1330
6236 // because %A may have negative value.
6237 //
6238 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6239 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006240 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006241 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6242 else
6243 return 0;
6244 }
6245
6246 // The re-extended constant changed so the constant cannot be represented
6247 // in the shorter type. Consequently, we cannot emit a simple comparison.
6248
6249 // First, handle some easy cases. We know the result cannot be equal at this
6250 // point so handle the ICI.isEquality() cases
6251 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006252 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006253 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006254 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006255
6256 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6257 // should have been folded away previously and not enter in here.
6258 Value *Result;
6259 if (isSignedCmp) {
6260 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006261 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006262 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006263 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006264 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006265 } else {
6266 // We're performing an unsigned comparison.
6267 if (isSignedExt) {
6268 // We're performing an unsigned comp with a sign extended value.
6269 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006270 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006271 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6272 NegOne, ICI.getName()), ICI);
6273 } else {
6274 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006275 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006276 }
6277 }
6278
6279 // Finally, return the value computed.
6280 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6281 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6282 return ReplaceInstUsesWith(ICI, Result);
6283 } else {
6284 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6285 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6286 "ICmp should be folded!");
6287 if (Constant *CI = dyn_cast<Constant>(Result))
6288 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6289 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006290 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006291 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006292}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006293
Reid Spencer832254e2007-02-02 02:16:23 +00006294Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6295 return commonShiftTransforms(I);
6296}
6297
6298Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6299 return commonShiftTransforms(I);
6300}
6301
6302Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006303 if (Instruction *R = commonShiftTransforms(I))
6304 return R;
6305
6306 Value *Op0 = I.getOperand(0);
6307
6308 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6309 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6310 if (CSI->isAllOnesValue())
6311 return ReplaceInstUsesWith(I, CSI);
6312
6313 // See if we can turn a signed shr into an unsigned shr.
6314 if (MaskedValueIsZero(Op0,
6315 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006316 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006317
6318 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006319}
6320
6321Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6322 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006323 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006324
6325 // shl X, 0 == X and shr X, 0 == X
6326 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006327 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006328 Op0 == Constant::getNullValue(Op0->getType()))
6329 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006330
Reid Spencere4d87aa2006-12-23 06:05:41 +00006331 if (isa<UndefValue>(Op0)) {
6332 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006333 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006334 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006335 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6336 }
6337 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006338 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6339 return ReplaceInstUsesWith(I, Op0);
6340 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006341 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006342 }
6343
Chris Lattner2eefe512004-04-09 19:05:30 +00006344 // Try to fold constant and into select arguments.
6345 if (isa<Constant>(Op0))
6346 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006347 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006348 return R;
6349
Reid Spencerb83eb642006-10-20 07:07:24 +00006350 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006351 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6352 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006353 return 0;
6354}
6355
Reid Spencerb83eb642006-10-20 07:07:24 +00006356Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006357 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006358 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006359
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006360 // See if we can simplify any instructions used by the instruction whose sole
6361 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006362 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6363 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6364 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006365 KnownZero, KnownOne))
6366 return &I;
6367
Chris Lattner4d5542c2006-01-06 07:12:35 +00006368 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6369 // of a signed value.
6370 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006371 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006372 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006373 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6374 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006375 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006376 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006377 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006378 }
6379
6380 // ((X*C1) << C2) == (X * (C1 << C2))
6381 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6382 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6383 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006384 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006385 ConstantExpr::getShl(BOOp, Op1));
6386
6387 // Try to fold constant and into select arguments.
6388 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6389 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6390 return R;
6391 if (isa<PHINode>(Op0))
6392 if (Instruction *NV = FoldOpIntoPhi(I))
6393 return NV;
6394
Chris Lattner8999dd32007-12-22 09:07:47 +00006395 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6396 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6397 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6398 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6399 // place. Don't try to do this transformation in this case. Also, we
6400 // require that the input operand is a shift-by-constant so that we have
6401 // confidence that the shifts will get folded together. We could do this
6402 // xform in more cases, but it is unlikely to be profitable.
6403 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6404 isa<ConstantInt>(TrOp->getOperand(1))) {
6405 // Okay, we'll do this xform. Make the shift of shift.
6406 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006407 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006408 I.getName());
6409 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6410
6411 // For logical shifts, the truncation has the effect of making the high
6412 // part of the register be zeros. Emulate this by inserting an AND to
6413 // clear the top bits as needed. This 'and' will usually be zapped by
6414 // other xforms later if dead.
6415 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6416 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6417 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6418
6419 // The mask we constructed says what the trunc would do if occurring
6420 // between the shifts. We want to know the effect *after* the second
6421 // shift. We know that it is a logical shift by a constant, so adjust the
6422 // mask as appropriate.
6423 if (I.getOpcode() == Instruction::Shl)
6424 MaskV <<= Op1->getZExtValue();
6425 else {
6426 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6427 MaskV = MaskV.lshr(Op1->getZExtValue());
6428 }
6429
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006430 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006431 TI->getName());
6432 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6433
6434 // Return the value truncated to the interesting size.
6435 return new TruncInst(And, I.getType());
6436 }
6437 }
6438
Chris Lattner4d5542c2006-01-06 07:12:35 +00006439 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006440 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6441 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6442 Value *V1, *V2;
6443 ConstantInt *CC;
6444 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006445 default: break;
6446 case Instruction::Add:
6447 case Instruction::And:
6448 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006449 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006450 // These operators commute.
6451 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006452 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6453 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006454 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006455 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006456 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006457 Op0BO->getName());
6458 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006459 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006460 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006461 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006462 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006463 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006464 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006465 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006466 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006467
Chris Lattner150f12a2005-09-18 06:30:59 +00006468 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006469 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006470 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006471 match(Op0BOOp1,
6472 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006473 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6474 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006475 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006476 Op0BO->getOperand(0), Op1,
6477 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006478 InsertNewInstBefore(YS, I); // (Y << C)
6479 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006480 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006481 V1->getName()+".mask");
6482 InsertNewInstBefore(XM, I); // X & (CC << C)
6483
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006484 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006485 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006486 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006487
Reid Spencera07cb7d2007-02-02 14:41:37 +00006488 // FALL THROUGH.
6489 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006490 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006491 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6492 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006493 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006494 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006495 Op0BO->getOperand(1), Op1,
6496 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006497 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006498 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006499 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006500 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006501 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006502 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006503 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006504 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006505 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006506
Chris Lattner13d4ab42006-05-31 21:14:00 +00006507 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006508 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6509 match(Op0BO->getOperand(0),
6510 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006511 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006512 cast<BinaryOperator>(Op0BO->getOperand(0))
6513 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006514 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006515 Op0BO->getOperand(1), Op1,
6516 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006517 InsertNewInstBefore(YS, I); // (Y << C)
6518 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006519 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006520 V1->getName()+".mask");
6521 InsertNewInstBefore(XM, I); // X & (CC << C)
6522
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006523 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006524 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006525
Chris Lattner11021cb2005-09-18 05:12:10 +00006526 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006527 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006528 }
6529
6530
6531 // If the operand is an bitwise operator with a constant RHS, and the
6532 // shift is the only use, we can pull it out of the shift.
6533 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6534 bool isValid = true; // Valid only for And, Or, Xor
6535 bool highBitSet = false; // Transform if high bit of constant set?
6536
6537 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006538 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006539 case Instruction::Add:
6540 isValid = isLeftShift;
6541 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006542 case Instruction::Or:
6543 case Instruction::Xor:
6544 highBitSet = false;
6545 break;
6546 case Instruction::And:
6547 highBitSet = true;
6548 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006549 }
6550
6551 // If this is a signed shift right, and the high bit is modified
6552 // by the logical operation, do not perform the transformation.
6553 // The highBitSet boolean indicates the value of the high bit of
6554 // the constant which would cause it to be modified for this
6555 // operation.
6556 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006557 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006558 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006559
6560 if (isValid) {
6561 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6562
6563 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006564 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006565 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006566 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006567
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006568 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006569 NewRHS);
6570 }
6571 }
6572 }
6573 }
6574
Chris Lattnerad0124c2006-01-06 07:52:12 +00006575 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006576 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6577 if (ShiftOp && !ShiftOp->isShift())
6578 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006579
Reid Spencerb83eb642006-10-20 07:07:24 +00006580 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006581 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006582 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6583 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006584 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6585 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6586 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006587
Zhou Sheng4351c642007-04-02 08:20:41 +00006588 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006589 if (AmtSum > TypeBits)
6590 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006591
6592 const IntegerType *Ty = cast<IntegerType>(I.getType());
6593
6594 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006595 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006596 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006597 ConstantInt::get(Ty, AmtSum));
6598 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6599 I.getOpcode() == Instruction::AShr) {
6600 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006601 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006602 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6603 I.getOpcode() == Instruction::LShr) {
6604 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6605 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006606 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006607 InsertNewInstBefore(Shift, I);
6608
Zhou Shenge9e03f62007-03-28 15:02:20 +00006609 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006610 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006611 }
6612
Chris Lattnerb87056f2007-02-05 00:57:54 +00006613 // Okay, if we get here, one shift must be left, and the other shift must be
6614 // right. See if the amounts are equal.
6615 if (ShiftAmt1 == ShiftAmt2) {
6616 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6617 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006618 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006619 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006620 }
6621 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6622 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006623 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006624 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006625 }
6626 // We can simplify ((X << C) >>s C) into a trunc + sext.
6627 // NOTE: we could do this for any C, but that would make 'unusual' integer
6628 // types. For now, just stick to ones well-supported by the code
6629 // generators.
6630 const Type *SExtType = 0;
6631 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006632 case 1 :
6633 case 8 :
6634 case 16 :
6635 case 32 :
6636 case 64 :
6637 case 128:
6638 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6639 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006640 default: break;
6641 }
6642 if (SExtType) {
6643 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6644 InsertNewInstBefore(NewTrunc, I);
6645 return new SExtInst(NewTrunc, Ty);
6646 }
6647 // Otherwise, we can't handle it yet.
6648 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006649 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006650
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006651 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006652 if (I.getOpcode() == Instruction::Shl) {
6653 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6654 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006655 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006656 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006657 InsertNewInstBefore(Shift, I);
6658
Reid Spencer55702aa2007-03-25 21:11:44 +00006659 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006660 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006661 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006662
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006663 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006664 if (I.getOpcode() == Instruction::LShr) {
6665 assert(ShiftOp->getOpcode() == Instruction::Shl);
6666 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006667 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006668 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006669
Reid Spencerd5e30f02007-03-26 17:18:58 +00006670 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006671 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006672 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006673
6674 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6675 } else {
6676 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006677 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006678
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006679 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006680 if (I.getOpcode() == Instruction::Shl) {
6681 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6682 ShiftOp->getOpcode() == Instruction::AShr);
6683 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006684 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006685 ConstantInt::get(Ty, ShiftDiff));
6686 InsertNewInstBefore(Shift, I);
6687
Reid Spencer55702aa2007-03-25 21:11:44 +00006688 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006689 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006690 }
6691
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006692 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006693 if (I.getOpcode() == Instruction::LShr) {
6694 assert(ShiftOp->getOpcode() == Instruction::Shl);
6695 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006696 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006697 InsertNewInstBefore(Shift, I);
6698
Reid Spencer68d27cf2007-03-26 23:45:51 +00006699 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006700 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006701 }
6702
6703 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006704 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006705 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006706 return 0;
6707}
6708
Chris Lattnera1be5662002-05-02 17:06:02 +00006709
Chris Lattnercfd65102005-10-29 04:36:15 +00006710/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6711/// expression. If so, decompose it, returning some value X, such that Val is
6712/// X*Scale+Offset.
6713///
6714static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006715 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006716 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006717 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006718 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006719 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006720 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006721 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6722 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6723 if (I->getOpcode() == Instruction::Shl) {
6724 // This is a value scaled by '1 << the shift amt'.
6725 Scale = 1U << RHS->getZExtValue();
6726 Offset = 0;
6727 return I->getOperand(0);
6728 } else if (I->getOpcode() == Instruction::Mul) {
6729 // This value is scaled by 'RHS'.
6730 Scale = RHS->getZExtValue();
6731 Offset = 0;
6732 return I->getOperand(0);
6733 } else if (I->getOpcode() == Instruction::Add) {
6734 // We have X+C. Check to see if we really have (X*C2)+C1,
6735 // where C1 is divisible by C2.
6736 unsigned SubScale;
6737 Value *SubVal =
6738 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6739 Offset += RHS->getZExtValue();
6740 Scale = SubScale;
6741 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006742 }
6743 }
6744 }
6745
6746 // Otherwise, we can't look past this.
6747 Scale = 1;
6748 Offset = 0;
6749 return Val;
6750}
6751
6752
Chris Lattnerb3f83972005-10-24 06:03:58 +00006753/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6754/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006755Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006756 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006757 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006758
Chris Lattnerb53c2382005-10-24 06:22:12 +00006759 // Remove any uses of AI that are dead.
6760 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006761
Chris Lattnerb53c2382005-10-24 06:22:12 +00006762 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6763 Instruction *User = cast<Instruction>(*UI++);
6764 if (isInstructionTriviallyDead(User)) {
6765 while (UI != E && *UI == User)
6766 ++UI; // If this instruction uses AI more than once, don't break UI.
6767
Chris Lattnerb53c2382005-10-24 06:22:12 +00006768 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006769 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006770 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006771 }
6772 }
6773
Chris Lattnerb3f83972005-10-24 06:03:58 +00006774 // Get the type really allocated and the type casted to.
6775 const Type *AllocElTy = AI.getAllocatedType();
6776 const Type *CastElTy = PTy->getElementType();
6777 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006778
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006779 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6780 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006781 if (CastElTyAlign < AllocElTyAlign) return 0;
6782
Chris Lattner39387a52005-10-24 06:35:18 +00006783 // If the allocation has multiple uses, only promote it if we are strictly
6784 // increasing the alignment of the resultant allocation. If we keep it the
6785 // same, we open the door to infinite loops of various kinds.
6786 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6787
Duncan Sands514ab342007-11-01 20:53:16 +00006788 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6789 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006790 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006791
Chris Lattner455fcc82005-10-29 03:19:53 +00006792 // See if we can satisfy the modulus by pulling a scale out of the array
6793 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006794 unsigned ArraySizeScale;
6795 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006796 Value *NumElements = // See if the array size is a decomposable linear expr.
6797 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6798
Chris Lattner455fcc82005-10-29 03:19:53 +00006799 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6800 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006801 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6802 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006803
Chris Lattner455fcc82005-10-29 03:19:53 +00006804 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6805 Value *Amt = 0;
6806 if (Scale == 1) {
6807 Amt = NumElements;
6808 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006809 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006810 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6811 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006812 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006813 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006814 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006815 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00006816 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006817 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006818 }
6819
Jeff Cohen86796be2007-04-04 16:58:57 +00006820 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6821 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006822 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00006823 Amt = InsertNewInstBefore(Tmp, AI);
6824 }
6825
Chris Lattnerb3f83972005-10-24 06:03:58 +00006826 AllocationInst *New;
6827 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006828 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006829 else
Chris Lattner6934a042007-02-11 01:23:03 +00006830 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006831 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006832 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006833
6834 // If the allocation has multiple uses, insert a cast and change all things
6835 // that used it to use the new cast. This will also hack on CI, but it will
6836 // die soon.
6837 if (!AI.hasOneUse()) {
6838 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006839 // New is the allocation instruction, pointer typed. AI is the original
6840 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6841 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006842 InsertNewInstBefore(NewCast, AI);
6843 AI.replaceAllUsesWith(NewCast);
6844 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006845 return ReplaceInstUsesWith(CI, New);
6846}
6847
Chris Lattner70074e02006-05-13 02:06:03 +00006848/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006849/// and return it as type Ty without inserting any new casts and without
6850/// changing the computed value. This is used by code that tries to decide
6851/// whether promoting or shrinking integer operations to wider or smaller types
6852/// will allow us to eliminate a truncate or extend.
6853///
6854/// This is a truncation operation if Ty is smaller than V->getType(), or an
6855/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00006856bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6857 unsigned CastOpc,
6858 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006859 // We can always evaluate constants in another type.
6860 if (isa<ConstantInt>(V))
6861 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006862
6863 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006864 if (!I) return false;
6865
6866 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006867
Chris Lattner951626b2007-08-02 06:11:14 +00006868 // If this is an extension or truncate, we can often eliminate it.
6869 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6870 // If this is a cast from the destination type, we can trivially eliminate
6871 // it, and this will remove a cast overall.
6872 if (I->getOperand(0)->getType() == Ty) {
6873 // If the first operand is itself a cast, and is eliminable, do not count
6874 // this as an eliminable cast. We would prefer to eliminate those two
6875 // casts first.
6876 if (!isa<CastInst>(I->getOperand(0)))
6877 ++NumCastsRemoved;
6878 return true;
6879 }
6880 }
6881
6882 // We can't extend or shrink something that has multiple uses: doing so would
6883 // require duplicating the instruction in general, which isn't profitable.
6884 if (!I->hasOneUse()) return false;
6885
Chris Lattner70074e02006-05-13 02:06:03 +00006886 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006887 case Instruction::Add:
6888 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006889 case Instruction::And:
6890 case Instruction::Or:
6891 case Instruction::Xor:
6892 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006893 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6894 NumCastsRemoved) &&
6895 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6896 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006897
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006898 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006899 // A multiply can be truncated by truncating its operands.
6900 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6901 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6902 NumCastsRemoved) &&
6903 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6904 NumCastsRemoved);
6905
Chris Lattner46b96052006-11-29 07:18:39 +00006906 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006907 // If we are truncating the result of this SHL, and if it's a shift of a
6908 // constant amount, we can always perform a SHL in a smaller type.
6909 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006910 uint32_t BitWidth = Ty->getBitWidth();
6911 if (BitWidth < OrigTy->getBitWidth() &&
6912 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006913 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6914 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006915 }
6916 break;
6917 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006918 // If this is a truncate of a logical shr, we can truncate it to a smaller
6919 // lshr iff we know that the bits we would otherwise be shifting in are
6920 // already zeros.
6921 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006922 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6923 uint32_t BitWidth = Ty->getBitWidth();
6924 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006925 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006926 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6927 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006928 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6929 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006930 }
6931 }
Chris Lattner46b96052006-11-29 07:18:39 +00006932 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006933 case Instruction::ZExt:
6934 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006935 case Instruction::Trunc:
6936 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006937 // can safely replace it. Note that replacing it does not reduce the number
6938 // of casts in the input.
6939 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006940 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006941
Reid Spencer3da59db2006-11-27 01:05:10 +00006942 break;
6943 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006944 // TODO: Can handle more cases here.
6945 break;
6946 }
6947
6948 return false;
6949}
6950
6951/// EvaluateInDifferentType - Given an expression that
6952/// CanEvaluateInDifferentType returns true for, actually insert the code to
6953/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006954Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006955 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006956 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006957 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006958
6959 // Otherwise, it must be an instruction.
6960 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006961 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006962 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006963 case Instruction::Add:
6964 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006965 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006966 case Instruction::And:
6967 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006968 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006969 case Instruction::AShr:
6970 case Instruction::LShr:
6971 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006972 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006973 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006974 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00006975 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006976 break;
6977 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006978 case Instruction::Trunc:
6979 case Instruction::ZExt:
6980 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006981 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006982 // just return the source. There's no need to insert it because it is not
6983 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006984 if (I->getOperand(0)->getType() == Ty)
6985 return I->getOperand(0);
6986
Chris Lattner951626b2007-08-02 06:11:14 +00006987 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006988 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00006989 Ty, I->getName());
6990 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006991 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006992 // TODO: Can handle more cases here.
6993 assert(0 && "Unreachable!");
6994 break;
6995 }
6996
6997 return InsertNewInstBefore(Res, *I);
6998}
6999
Reid Spencer3da59db2006-11-27 01:05:10 +00007000/// @brief Implement the transforms common to all CastInst visitors.
7001Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007002 Value *Src = CI.getOperand(0);
7003
Dan Gohman23d9d272007-05-11 21:10:54 +00007004 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007005 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007006 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007007 if (Instruction::CastOps opc =
7008 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7009 // The first cast (CSrc) is eliminable so we need to fix up or replace
7010 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007011 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007012 }
7013 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007014
Reid Spencer3da59db2006-11-27 01:05:10 +00007015 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007016 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7017 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7018 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007019
7020 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007021 if (isa<PHINode>(Src))
7022 if (Instruction *NV = FoldOpIntoPhi(CI))
7023 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007024
Reid Spencer3da59db2006-11-27 01:05:10 +00007025 return 0;
7026}
7027
Chris Lattnerd3e28342007-04-27 17:44:50 +00007028/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7029Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7030 Value *Src = CI.getOperand(0);
7031
Chris Lattnerd3e28342007-04-27 17:44:50 +00007032 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007033 // If casting the result of a getelementptr instruction with no offset, turn
7034 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007035 if (GEP->hasAllZeroIndices()) {
7036 // Changing the cast operand is usually not a good idea but it is safe
7037 // here because the pointer operand is being replaced with another
7038 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007039 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007040 CI.setOperand(0, GEP->getOperand(0));
7041 return &CI;
7042 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007043
7044 // If the GEP has a single use, and the base pointer is a bitcast, and the
7045 // GEP computes a constant offset, see if we can convert these three
7046 // instructions into fewer. This typically happens with unions and other
7047 // non-type-safe code.
7048 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7049 if (GEP->hasAllConstantIndices()) {
7050 // We are guaranteed to get a constant from EmitGEPOffset.
7051 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7052 int64_t Offset = OffsetV->getSExtValue();
7053
7054 // Get the base pointer input of the bitcast, and the type it points to.
7055 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7056 const Type *GEPIdxTy =
7057 cast<PointerType>(OrigBase->getType())->getElementType();
7058 if (GEPIdxTy->isSized()) {
7059 SmallVector<Value*, 8> NewIndices;
7060
Chris Lattnerc42e2262007-05-05 01:59:31 +00007061 // Start with the index over the outer type. Note that the type size
7062 // might be zero (even if the offset isn't zero) if the indexed type
7063 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007064 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007065 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007066 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007067 FirstIdx = Offset/TySize;
7068 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007069
Chris Lattnerc42e2262007-05-05 01:59:31 +00007070 // Handle silly modulus not returning values values [0..TySize).
7071 if (Offset < 0) {
7072 --FirstIdx;
7073 Offset += TySize;
7074 assert(Offset >= 0);
7075 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007076 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007077 }
7078
7079 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007080
7081 // Index into the types. If we fail, set OrigBase to null.
7082 while (Offset) {
7083 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7084 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007085 if (Offset < (int64_t)SL->getSizeInBytes()) {
7086 unsigned Elt = SL->getElementContainingOffset(Offset);
7087 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007088
Chris Lattner6b6aef82007-05-15 00:16:00 +00007089 Offset -= SL->getElementOffset(Elt);
7090 GEPIdxTy = STy->getElementType(Elt);
7091 } else {
7092 // Otherwise, we can't index into this, bail out.
7093 Offset = 0;
7094 OrigBase = 0;
7095 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007096 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7097 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007098 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007099 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7100 Offset %= EltSize;
7101 } else {
7102 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7103 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007104 GEPIdxTy = STy->getElementType();
7105 } else {
7106 // Otherwise, we can't index into this, bail out.
7107 Offset = 0;
7108 OrigBase = 0;
7109 }
7110 }
7111 if (OrigBase) {
7112 // If we were able to index down into an element, create the GEP
7113 // and bitcast the result. This eliminates one bitcast, potentially
7114 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007115 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7116 NewIndices.begin(),
7117 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007118 InsertNewInstBefore(NGEP, CI);
7119 NGEP->takeName(GEP);
7120
Chris Lattner9bc14642007-04-28 00:57:34 +00007121 if (isa<BitCastInst>(CI))
7122 return new BitCastInst(NGEP, CI.getType());
7123 assert(isa<PtrToIntInst>(CI));
7124 return new PtrToIntInst(NGEP, CI.getType());
7125 }
7126 }
7127 }
7128 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007129 }
7130
7131 return commonCastTransforms(CI);
7132}
7133
7134
7135
Chris Lattnerc739cd62007-03-03 05:27:34 +00007136/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7137/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007138/// cases.
7139/// @brief Implement the transforms common to CastInst with integer operands
7140Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7141 if (Instruction *Result = commonCastTransforms(CI))
7142 return Result;
7143
7144 Value *Src = CI.getOperand(0);
7145 const Type *SrcTy = Src->getType();
7146 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007147 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7148 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007149
Reid Spencer3da59db2006-11-27 01:05:10 +00007150 // See if we can simplify any instructions used by the LHS whose sole
7151 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007152 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7153 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007154 KnownZero, KnownOne))
7155 return &CI;
7156
7157 // If the source isn't an instruction or has more than one use then we
7158 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007159 Instruction *SrcI = dyn_cast<Instruction>(Src);
7160 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007161 return 0;
7162
Chris Lattnerc739cd62007-03-03 05:27:34 +00007163 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007164 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007165 if (!isa<BitCastInst>(CI) &&
7166 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007167 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007168 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007169 // eliminates the cast, so it is always a win. If this is a zero-extension,
7170 // we need to do an AND to maintain the clear top-part of the computation,
7171 // so we require that the input have eliminated at least one cast. If this
7172 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007173 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007174 bool DoXForm;
7175 switch (CI.getOpcode()) {
7176 default:
7177 // All the others use floating point so we shouldn't actually
7178 // get here because of the check above.
7179 assert(0 && "Unknown cast type");
7180 case Instruction::Trunc:
7181 DoXForm = true;
7182 break;
7183 case Instruction::ZExt:
7184 DoXForm = NumCastsRemoved >= 1;
7185 break;
7186 case Instruction::SExt:
7187 DoXForm = NumCastsRemoved >= 2;
7188 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007189 }
7190
7191 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007192 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7193 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007194 assert(Res->getType() == DestTy);
7195 switch (CI.getOpcode()) {
7196 default: assert(0 && "Unknown cast type!");
7197 case Instruction::Trunc:
7198 case Instruction::BitCast:
7199 // Just replace this cast with the result.
7200 return ReplaceInstUsesWith(CI, Res);
7201 case Instruction::ZExt: {
7202 // We need to emit an AND to clear the high bits.
7203 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007204 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7205 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007206 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007207 }
7208 case Instruction::SExt:
7209 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007210 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007211 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7212 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007213 }
7214 }
7215 }
7216
7217 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7218 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7219
7220 switch (SrcI->getOpcode()) {
7221 case Instruction::Add:
7222 case Instruction::Mul:
7223 case Instruction::And:
7224 case Instruction::Or:
7225 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007226 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007227 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7228 // Don't insert two casts if they cannot be eliminated. We allow
7229 // two casts to be inserted if the sizes are the same. This could
7230 // only be converting signedness, which is a noop.
7231 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007232 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7233 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007234 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007235 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7236 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007237 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007238 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007239 }
7240 }
7241
7242 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7243 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7244 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007245 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007246 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007247 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007248 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007249 }
7250 break;
7251 case Instruction::SDiv:
7252 case Instruction::UDiv:
7253 case Instruction::SRem:
7254 case Instruction::URem:
7255 // If we are just changing the sign, rewrite.
7256 if (DestBitSize == SrcBitSize) {
7257 // Don't insert two casts if they cannot be eliminated. We allow
7258 // two casts to be inserted if the sizes are the same. This could
7259 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007260 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7261 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007262 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7263 Op0, DestTy, SrcI);
7264 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7265 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007266 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007267 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7268 }
7269 }
7270 break;
7271
7272 case Instruction::Shl:
7273 // Allow changing the sign of the source operand. Do not allow
7274 // changing the size of the shift, UNLESS the shift amount is a
7275 // constant. We must not change variable sized shifts to a smaller
7276 // size, because it is undefined to shift more bits out than exist
7277 // in the value.
7278 if (DestBitSize == SrcBitSize ||
7279 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007280 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7281 Instruction::BitCast : Instruction::Trunc);
7282 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007283 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007284 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007285 }
7286 break;
7287 case Instruction::AShr:
7288 // If this is a signed shr, and if all bits shifted in are about to be
7289 // truncated off, turn it into an unsigned shr to allow greater
7290 // simplifications.
7291 if (DestBitSize < SrcBitSize &&
7292 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007293 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007294 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7295 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007296 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007297 }
7298 }
7299 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007300 }
7301 return 0;
7302}
7303
Chris Lattner8a9f5712007-04-11 06:57:46 +00007304Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007305 if (Instruction *Result = commonIntCastTransforms(CI))
7306 return Result;
7307
7308 Value *Src = CI.getOperand(0);
7309 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007310 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7311 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007312
7313 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7314 switch (SrcI->getOpcode()) {
7315 default: break;
7316 case Instruction::LShr:
7317 // We can shrink lshr to something smaller if we know the bits shifted in
7318 // are already zeros.
7319 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007320 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007321
7322 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007323 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007324 Value* SrcIOp0 = SrcI->getOperand(0);
7325 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007326 if (ShAmt >= DestBitWidth) // All zeros.
7327 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7328
7329 // Okay, we can shrink this. Truncate the input, then return a new
7330 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007331 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7332 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7333 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007334 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007335 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007336 } else { // This is a variable shr.
7337
7338 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7339 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7340 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007341 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007342 Value *One = ConstantInt::get(SrcI->getType(), 1);
7343
Reid Spencer832254e2007-02-02 02:16:23 +00007344 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007345 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007346 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007347 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007348 SrcI->getOperand(0),
7349 "tmp"), CI);
7350 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007351 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007352 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007353 }
7354 break;
7355 }
7356 }
7357
7358 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007359}
7360
Evan Chengb98a10e2008-03-24 00:21:34 +00007361/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7362/// in order to eliminate the icmp.
7363Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7364 bool DoXform) {
7365 // If we are just checking for a icmp eq of a single bit and zext'ing it
7366 // to an integer, then shift the bit to the appropriate place and then
7367 // cast to integer to avoid the comparison.
7368 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7369 const APInt &Op1CV = Op1C->getValue();
7370
7371 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7372 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7373 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7374 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7375 if (!DoXform) return ICI;
7376
7377 Value *In = ICI->getOperand(0);
7378 Value *Sh = ConstantInt::get(In->getType(),
7379 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007380 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007381 In->getName()+".lobit"),
7382 CI);
7383 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007384 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007385 false/*ZExt*/, "tmp", &CI);
7386
7387 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7388 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007389 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007390 In->getName()+".not"),
7391 CI);
7392 }
7393
7394 return ReplaceInstUsesWith(CI, In);
7395 }
7396
7397
7398
7399 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7400 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7401 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7402 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7403 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7404 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7405 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7406 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7407 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7408 // This only works for EQ and NE
7409 ICI->isEquality()) {
7410 // If Op1C some other power of two, convert:
7411 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7412 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7413 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7414 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7415
7416 APInt KnownZeroMask(~KnownZero);
7417 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7418 if (!DoXform) return ICI;
7419
7420 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7421 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7422 // (X&4) == 2 --> false
7423 // (X&4) != 2 --> true
7424 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7425 Res = ConstantExpr::getZExt(Res, CI.getType());
7426 return ReplaceInstUsesWith(CI, Res);
7427 }
7428
7429 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7430 Value *In = ICI->getOperand(0);
7431 if (ShiftAmt) {
7432 // Perform a logical shr by shiftamt.
7433 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007434 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007435 ConstantInt::get(In->getType(), ShiftAmt),
7436 In->getName()+".lobit"), CI);
7437 }
7438
7439 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7440 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007441 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007442 InsertNewInstBefore(cast<Instruction>(In), CI);
7443 }
7444
7445 if (CI.getType() == In->getType())
7446 return ReplaceInstUsesWith(CI, In);
7447 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007448 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007449 }
7450 }
7451 }
7452
7453 return 0;
7454}
7455
Chris Lattner8a9f5712007-04-11 06:57:46 +00007456Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007457 // If one of the common conversion will work ..
7458 if (Instruction *Result = commonIntCastTransforms(CI))
7459 return Result;
7460
7461 Value *Src = CI.getOperand(0);
7462
7463 // If this is a cast of a cast
7464 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007465 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7466 // types and if the sizes are just right we can convert this into a logical
7467 // 'and' which will be much cheaper than the pair of casts.
7468 if (isa<TruncInst>(CSrc)) {
7469 // Get the sizes of the types involved
7470 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007471 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7472 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7473 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007474 // If we're actually extending zero bits and the trunc is a no-op
7475 if (MidSize < DstSize && SrcSize == DstSize) {
7476 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007477 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007478 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007479 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007480 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007481 // Unfortunately, if the type changed, we need to cast it back.
7482 if (And->getType() != CI.getType()) {
7483 And->setName(CSrc->getName()+".mask");
7484 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007485 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007486 }
7487 return And;
7488 }
7489 }
7490 }
7491
Evan Chengb98a10e2008-03-24 00:21:34 +00007492 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7493 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007494
Evan Chengb98a10e2008-03-24 00:21:34 +00007495 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7496 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7497 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7498 // of the (zext icmp) will be transformed.
7499 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7500 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7501 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7502 (transformZExtICmp(LHS, CI, false) ||
7503 transformZExtICmp(RHS, CI, false))) {
7504 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7505 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007506 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007507 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007508 }
7509
Reid Spencer3da59db2006-11-27 01:05:10 +00007510 return 0;
7511}
7512
Chris Lattner8a9f5712007-04-11 06:57:46 +00007513Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007514 if (Instruction *I = commonIntCastTransforms(CI))
7515 return I;
7516
Chris Lattner8a9f5712007-04-11 06:57:46 +00007517 Value *Src = CI.getOperand(0);
7518
7519 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7520 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7521 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7522 // If we are just checking for a icmp eq of a single bit and zext'ing it
7523 // to an integer, then shift the bit to the appropriate place and then
7524 // cast to integer to avoid the comparison.
7525 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7526 const APInt &Op1CV = Op1C->getValue();
7527
7528 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7529 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7530 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7531 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7532 Value *In = ICI->getOperand(0);
7533 Value *Sh = ConstantInt::get(In->getType(),
7534 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007535 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007536 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007537 CI);
7538 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007539 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007540 true/*SExt*/, "tmp", &CI);
7541
7542 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007543 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007544 In->getName()+".not"), CI);
7545
7546 return ReplaceInstUsesWith(CI, In);
7547 }
7548 }
7549 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00007550
7551 // See if the value being truncated is already sign extended. If so, just
7552 // eliminate the trunc/sext pair.
7553 if (getOpcode(Src) == Instruction::Trunc) {
7554 Value *Op = cast<User>(Src)->getOperand(0);
7555 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7556 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7557 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7558 unsigned NumSignBits = ComputeNumSignBits(Op);
7559
7560 if (OpBits == DestBits) {
7561 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7562 // bits, it is already ready.
7563 if (NumSignBits > DestBits-MidBits)
7564 return ReplaceInstUsesWith(CI, Op);
7565 } else if (OpBits < DestBits) {
7566 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7567 // bits, just sext from i32.
7568 if (NumSignBits > OpBits-MidBits)
7569 return new SExtInst(Op, CI.getType(), "tmp");
7570 } else {
7571 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7572 // bits, just truncate to i32.
7573 if (NumSignBits > OpBits-MidBits)
7574 return new TruncInst(Op, CI.getType(), "tmp");
7575 }
7576 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00007577
Chris Lattnerba417832007-04-11 06:12:58 +00007578 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007579}
7580
Chris Lattnerb7530652008-01-27 05:29:54 +00007581/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7582/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007583static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007584 APFloat F = CFP->getValueAPF();
7585 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007586 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007587 return 0;
7588}
7589
7590/// LookThroughFPExtensions - If this is an fp extension instruction, look
7591/// through it until we get the source value.
7592static Value *LookThroughFPExtensions(Value *V) {
7593 if (Instruction *I = dyn_cast<Instruction>(V))
7594 if (I->getOpcode() == Instruction::FPExt)
7595 return LookThroughFPExtensions(I->getOperand(0));
7596
7597 // If this value is a constant, return the constant in the smallest FP type
7598 // that can accurately represent it. This allows us to turn
7599 // (float)((double)X+2.0) into x+2.0f.
7600 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7601 if (CFP->getType() == Type::PPC_FP128Ty)
7602 return V; // No constant folding of this.
7603 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007604 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007605 return V;
7606 if (CFP->getType() == Type::DoubleTy)
7607 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007608 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007609 return V;
7610 // Don't try to shrink to various long double types.
7611 }
7612
7613 return V;
7614}
7615
7616Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7617 if (Instruction *I = commonCastTransforms(CI))
7618 return I;
7619
7620 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7621 // smaller than the destination type, we can eliminate the truncate by doing
7622 // the add as the smaller type. This applies to add/sub/mul/div as well as
7623 // many builtins (sqrt, etc).
7624 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7625 if (OpI && OpI->hasOneUse()) {
7626 switch (OpI->getOpcode()) {
7627 default: break;
7628 case Instruction::Add:
7629 case Instruction::Sub:
7630 case Instruction::Mul:
7631 case Instruction::FDiv:
7632 case Instruction::FRem:
7633 const Type *SrcTy = OpI->getType();
7634 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7635 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7636 if (LHSTrunc->getType() != SrcTy &&
7637 RHSTrunc->getType() != SrcTy) {
7638 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7639 // If the source types were both smaller than the destination type of
7640 // the cast, do this xform.
7641 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7642 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7643 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7644 CI.getType(), CI);
7645 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7646 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007647 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007648 }
7649 }
7650 break;
7651 }
7652 }
7653 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007654}
7655
7656Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7657 return commonCastTransforms(CI);
7658}
7659
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007660Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7661 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7662 // mantissa to accurately represent all values of X. For example, do not
7663 // do this with i64->float->i64.
7664 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7665 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7666 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00007667 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007668 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7669
7670 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007671}
7672
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007673Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7674 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7675 // mantissa to accurately represent all values of X. For example, do not
7676 // do this with i64->float->i64.
7677 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7678 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7679 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00007680 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007681 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7682
7683 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007684}
7685
7686Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7687 return commonCastTransforms(CI);
7688}
7689
7690Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7691 return commonCastTransforms(CI);
7692}
7693
7694Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007695 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007696}
7697
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007698Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7699 if (Instruction *I = commonCastTransforms(CI))
7700 return I;
7701
7702 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7703 if (!DestPointee->isSized()) return 0;
7704
7705 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7706 ConstantInt *Cst;
7707 Value *X;
7708 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7709 m_ConstantInt(Cst)))) {
7710 // If the source and destination operands have the same type, see if this
7711 // is a single-index GEP.
7712 if (X->getType() == CI.getType()) {
7713 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007714 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007715
7716 // Convert the constant to intptr type.
7717 APInt Offset = Cst->getValue();
7718 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7719
7720 // If Offset is evenly divisible by Size, we can do this xform.
7721 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7722 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007723 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007724 }
7725 }
7726 // TODO: Could handle other cases, e.g. where add is indexing into field of
7727 // struct etc.
7728 } else if (CI.getOperand(0)->hasOneUse() &&
7729 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7730 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7731 // "inttoptr+GEP" instead of "add+intptr".
7732
7733 // Get the size of the pointee type.
7734 uint64_t Size = TD->getABITypeSize(DestPointee);
7735
7736 // Convert the constant to intptr type.
7737 APInt Offset = Cst->getValue();
7738 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7739
7740 // If Offset is evenly divisible by Size, we can do this xform.
7741 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7742 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7743
7744 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7745 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007746 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007747 }
7748 }
7749 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007750}
7751
Chris Lattnerd3e28342007-04-27 17:44:50 +00007752Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007753 // If the operands are integer typed then apply the integer transforms,
7754 // otherwise just apply the common ones.
7755 Value *Src = CI.getOperand(0);
7756 const Type *SrcTy = Src->getType();
7757 const Type *DestTy = CI.getType();
7758
Chris Lattner42a75512007-01-15 02:27:26 +00007759 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007760 if (Instruction *Result = commonIntCastTransforms(CI))
7761 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007762 } else if (isa<PointerType>(SrcTy)) {
7763 if (Instruction *I = commonPointerCastTransforms(CI))
7764 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007765 } else {
7766 if (Instruction *Result = commonCastTransforms(CI))
7767 return Result;
7768 }
7769
7770
7771 // Get rid of casts from one type to the same type. These are useless and can
7772 // be replaced by the operand.
7773 if (DestTy == Src->getType())
7774 return ReplaceInstUsesWith(CI, Src);
7775
Reid Spencer3da59db2006-11-27 01:05:10 +00007776 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007777 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7778 const Type *DstElTy = DstPTy->getElementType();
7779 const Type *SrcElTy = SrcPTy->getElementType();
7780
Nate Begeman83ad90a2008-03-31 00:22:16 +00007781 // If the address spaces don't match, don't eliminate the bitcast, which is
7782 // required for changing types.
7783 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7784 return 0;
7785
Chris Lattnerd3e28342007-04-27 17:44:50 +00007786 // If we are casting a malloc or alloca to a pointer to a type of the same
7787 // size, rewrite the allocation instruction to allocate the "right" type.
7788 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7789 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7790 return V;
7791
Chris Lattnerd717c182007-05-05 22:32:24 +00007792 // If the source and destination are pointers, and this cast is equivalent
7793 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007794 // This can enhance SROA and other transforms that want type-safe pointers.
7795 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7796 unsigned NumZeros = 0;
7797 while (SrcElTy != DstElTy &&
7798 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7799 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7800 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7801 ++NumZeros;
7802 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007803
Chris Lattnerd3e28342007-04-27 17:44:50 +00007804 // If we found a path from the src to dest, create the getelementptr now.
7805 if (SrcElTy == DstElTy) {
7806 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007807 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7808 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007809 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007810 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007811
Reid Spencer3da59db2006-11-27 01:05:10 +00007812 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7813 if (SVI->hasOneUse()) {
7814 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7815 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007816 if (isa<VectorType>(DestTy) &&
7817 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007818 SVI->getType()->getNumElements()) {
7819 CastInst *Tmp;
7820 // If either of the operands is a cast from CI.getType(), then
7821 // evaluating the shuffle in the casted destination's type will allow
7822 // us to eliminate at least one cast.
7823 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7824 Tmp->getOperand(0)->getType() == DestTy) ||
7825 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7826 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007827 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7828 SVI->getOperand(0), DestTy, &CI);
7829 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7830 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007831 // Return a new shuffle vector. Use the same element ID's, as we
7832 // know the vector types match #elts.
7833 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007834 }
7835 }
7836 }
7837 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007838 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007839}
7840
Chris Lattnere576b912004-04-09 23:46:01 +00007841/// GetSelectFoldableOperands - We want to turn code that looks like this:
7842/// %C = or %A, %B
7843/// %D = select %cond, %C, %A
7844/// into:
7845/// %C = select %cond, %B, 0
7846/// %D = or %A, %C
7847///
7848/// Assuming that the specified instruction is an operand to the select, return
7849/// a bitmask indicating which operands of this instruction are foldable if they
7850/// equal the other incoming value of the select.
7851///
7852static unsigned GetSelectFoldableOperands(Instruction *I) {
7853 switch (I->getOpcode()) {
7854 case Instruction::Add:
7855 case Instruction::Mul:
7856 case Instruction::And:
7857 case Instruction::Or:
7858 case Instruction::Xor:
7859 return 3; // Can fold through either operand.
7860 case Instruction::Sub: // Can only fold on the amount subtracted.
7861 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007862 case Instruction::LShr:
7863 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007864 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007865 default:
7866 return 0; // Cannot fold
7867 }
7868}
7869
7870/// GetSelectFoldableConstant - For the same transformation as the previous
7871/// function, return the identity constant that goes into the select.
7872static Constant *GetSelectFoldableConstant(Instruction *I) {
7873 switch (I->getOpcode()) {
7874 default: assert(0 && "This cannot happen!"); abort();
7875 case Instruction::Add:
7876 case Instruction::Sub:
7877 case Instruction::Or:
7878 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007879 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007880 case Instruction::LShr:
7881 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007882 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007883 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007884 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007885 case Instruction::Mul:
7886 return ConstantInt::get(I->getType(), 1);
7887 }
7888}
7889
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007890/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7891/// have the same opcode and only one use each. Try to simplify this.
7892Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7893 Instruction *FI) {
7894 if (TI->getNumOperands() == 1) {
7895 // If this is a non-volatile load or a cast from the same type,
7896 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007897 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007898 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7899 return 0;
7900 } else {
7901 return 0; // unknown unary op.
7902 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007903
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007904 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00007905 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7906 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007907 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007908 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00007909 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007910 }
7911
Reid Spencer832254e2007-02-02 02:16:23 +00007912 // Only handle binary operators here.
7913 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007914 return 0;
7915
7916 // Figure out if the operations have any operands in common.
7917 Value *MatchOp, *OtherOpT, *OtherOpF;
7918 bool MatchIsOpZero;
7919 if (TI->getOperand(0) == FI->getOperand(0)) {
7920 MatchOp = TI->getOperand(0);
7921 OtherOpT = TI->getOperand(1);
7922 OtherOpF = FI->getOperand(1);
7923 MatchIsOpZero = true;
7924 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7925 MatchOp = TI->getOperand(1);
7926 OtherOpT = TI->getOperand(0);
7927 OtherOpF = FI->getOperand(0);
7928 MatchIsOpZero = false;
7929 } else if (!TI->isCommutative()) {
7930 return 0;
7931 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7932 MatchOp = TI->getOperand(0);
7933 OtherOpT = TI->getOperand(1);
7934 OtherOpF = FI->getOperand(0);
7935 MatchIsOpZero = true;
7936 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7937 MatchOp = TI->getOperand(1);
7938 OtherOpT = TI->getOperand(0);
7939 OtherOpF = FI->getOperand(1);
7940 MatchIsOpZero = true;
7941 } else {
7942 return 0;
7943 }
7944
7945 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00007946 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
7947 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007948 InsertNewInstBefore(NewSI, SI);
7949
7950 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7951 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007952 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007953 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007954 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007955 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007956 assert(0 && "Shouldn't get here");
7957 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007958}
7959
Chris Lattner3d69f462004-03-12 05:52:32 +00007960Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007961 Value *CondVal = SI.getCondition();
7962 Value *TrueVal = SI.getTrueValue();
7963 Value *FalseVal = SI.getFalseValue();
7964
7965 // select true, X, Y -> X
7966 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007967 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007968 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007969
7970 // select C, X, X -> X
7971 if (TrueVal == FalseVal)
7972 return ReplaceInstUsesWith(SI, TrueVal);
7973
Chris Lattnere87597f2004-10-16 18:11:37 +00007974 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7975 return ReplaceInstUsesWith(SI, FalseVal);
7976 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7977 return ReplaceInstUsesWith(SI, TrueVal);
7978 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7979 if (isa<Constant>(TrueVal))
7980 return ReplaceInstUsesWith(SI, TrueVal);
7981 else
7982 return ReplaceInstUsesWith(SI, FalseVal);
7983 }
7984
Reid Spencer4fe16d62007-01-11 18:21:29 +00007985 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007986 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007987 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007988 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007989 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007990 } else {
7991 // Change: A = select B, false, C --> A = and !B, C
7992 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007993 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00007994 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007995 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007996 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007997 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007998 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007999 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008000 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008001 } else {
8002 // Change: A = select B, C, true --> A = or !B, C
8003 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008004 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008005 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008006 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008007 }
8008 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008009
8010 // select a, b, a -> a&b
8011 // select a, a, b -> a|b
8012 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008013 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008014 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008015 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008016 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008017
Chris Lattner2eefe512004-04-09 19:05:30 +00008018 // Selecting between two integer constants?
8019 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8020 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008021 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008022 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008023 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008024 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008025 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008026 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008027 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008028 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008029 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008030 }
Chris Lattnerba417832007-04-11 06:12:58 +00008031
8032 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008033
Reid Spencere4d87aa2006-12-23 06:05:41 +00008034 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008035
Reid Spencere4d87aa2006-12-23 06:05:41 +00008036 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008037 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008038 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008039 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008040 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008041 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008042 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008043 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008044 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008045 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008046 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008047 InsertNewInstBefore(SRA, SI);
8048
Reid Spencer3da59db2006-11-27 01:05:10 +00008049 // Finally, convert to the type of the select RHS. We figure out
8050 // if this requires a SExt, Trunc or BitCast based on the sizes.
8051 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008052 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8053 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008054 if (SRASize < SISize)
8055 opc = Instruction::SExt;
8056 else if (SRASize > SISize)
8057 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008058 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008059 }
8060 }
8061
8062
8063 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008064 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008065 // non-constant value, eliminate this whole mess. This corresponds to
8066 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008067 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008068 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008069 cast<Constant>(IC->getOperand(1))->isNullValue())
8070 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8071 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008072 isa<ConstantInt>(ICA->getOperand(1)) &&
8073 (ICA->getOperand(1) == TrueValC ||
8074 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008075 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8076 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008077 // know whether we have a icmp_ne or icmp_eq and whether the
8078 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008079 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008080 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008081 Value *V = ICA;
8082 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008083 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008084 Instruction::Xor, V, ICA->getOperand(1)), SI);
8085 return ReplaceInstUsesWith(SI, V);
8086 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008087 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008088 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008089
8090 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008091 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8092 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008093 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008094 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8095 // This is not safe in general for floating point:
8096 // consider X== -0, Y== +0.
8097 // It becomes safe if either operand is a nonzero constant.
8098 ConstantFP *CFPt, *CFPf;
8099 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8100 !CFPt->getValueAPF().isZero()) ||
8101 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8102 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008103 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008104 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008105 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008106 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008107 return ReplaceInstUsesWith(SI, TrueVal);
8108 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8109
Reid Spencere4d87aa2006-12-23 06:05:41 +00008110 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008111 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008112 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8113 // This is not safe in general for floating point:
8114 // consider X== -0, Y== +0.
8115 // It becomes safe if either operand is a nonzero constant.
8116 ConstantFP *CFPt, *CFPf;
8117 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8118 !CFPt->getValueAPF().isZero()) ||
8119 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8120 !CFPf->getValueAPF().isZero()))
8121 return ReplaceInstUsesWith(SI, FalseVal);
8122 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008123 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008124 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8125 return ReplaceInstUsesWith(SI, TrueVal);
8126 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8127 }
8128 }
8129
8130 // See if we are selecting two values based on a comparison of the two values.
8131 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8132 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8133 // Transform (X == Y) ? X : Y -> Y
8134 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8135 return ReplaceInstUsesWith(SI, FalseVal);
8136 // Transform (X != Y) ? X : Y -> X
8137 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8138 return ReplaceInstUsesWith(SI, TrueVal);
8139 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8140
8141 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8142 // Transform (X == Y) ? Y : X -> X
8143 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8144 return ReplaceInstUsesWith(SI, FalseVal);
8145 // Transform (X != Y) ? Y : X -> Y
8146 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008147 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008148 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8149 }
8150 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008151
Chris Lattner87875da2005-01-13 22:52:24 +00008152 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8153 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8154 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008155 Instruction *AddOp = 0, *SubOp = 0;
8156
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008157 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8158 if (TI->getOpcode() == FI->getOpcode())
8159 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8160 return IV;
8161
8162 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8163 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008164 if (TI->getOpcode() == Instruction::Sub &&
8165 FI->getOpcode() == Instruction::Add) {
8166 AddOp = FI; SubOp = TI;
8167 } else if (FI->getOpcode() == Instruction::Sub &&
8168 TI->getOpcode() == Instruction::Add) {
8169 AddOp = TI; SubOp = FI;
8170 }
8171
8172 if (AddOp) {
8173 Value *OtherAddOp = 0;
8174 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8175 OtherAddOp = AddOp->getOperand(1);
8176 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8177 OtherAddOp = AddOp->getOperand(0);
8178 }
8179
8180 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008181 // So at this point we know we have (Y -> OtherAddOp):
8182 // select C, (add X, Y), (sub X, Z)
8183 Value *NegVal; // Compute -Z
8184 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8185 NegVal = ConstantExpr::getNeg(C);
8186 } else {
8187 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008188 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008189 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008190
8191 Value *NewTrueOp = OtherAddOp;
8192 Value *NewFalseOp = NegVal;
8193 if (AddOp != TI)
8194 std::swap(NewTrueOp, NewFalseOp);
8195 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008196 SelectInst::Create(CondVal, NewTrueOp,
8197 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008198
8199 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008200 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008201 }
8202 }
8203 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008204
Chris Lattnere576b912004-04-09 23:46:01 +00008205 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008206 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008207 // See the comment above GetSelectFoldableOperands for a description of the
8208 // transformation we are doing here.
8209 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8210 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8211 !isa<Constant>(FalseVal))
8212 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8213 unsigned OpToFold = 0;
8214 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8215 OpToFold = 1;
8216 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8217 OpToFold = 2;
8218 }
8219
8220 if (OpToFold) {
8221 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008222 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008223 SelectInst::Create(SI.getCondition(),
8224 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008225 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008226 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008227 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008228 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008229 else {
8230 assert(0 && "Unknown instruction!!");
8231 }
8232 }
8233 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008234
Chris Lattnere576b912004-04-09 23:46:01 +00008235 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8236 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8237 !isa<Constant>(TrueVal))
8238 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8239 unsigned OpToFold = 0;
8240 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8241 OpToFold = 1;
8242 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8243 OpToFold = 2;
8244 }
8245
8246 if (OpToFold) {
8247 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008248 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008249 SelectInst::Create(SI.getCondition(), C,
8250 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008251 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008252 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008253 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008254 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008255 else
Chris Lattnere576b912004-04-09 23:46:01 +00008256 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008257 }
8258 }
8259 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008260
8261 if (BinaryOperator::isNot(CondVal)) {
8262 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8263 SI.setOperand(1, FalseVal);
8264 SI.setOperand(2, TrueVal);
8265 return &SI;
8266 }
8267
Chris Lattner3d69f462004-03-12 05:52:32 +00008268 return 0;
8269}
8270
Dan Gohmaneee962e2008-04-10 18:43:06 +00008271/// EnforceKnownAlignment - If the specified pointer points to an object that
8272/// we control, modify the object's alignment to PrefAlign. This isn't
8273/// often possible though. If alignment is important, a more reliable approach
8274/// is to simply align all global variables and allocation instructions to
8275/// their preferred alignment from the beginning.
8276///
8277static unsigned EnforceKnownAlignment(Value *V,
8278 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008279
Dan Gohmaneee962e2008-04-10 18:43:06 +00008280 User *U = dyn_cast<User>(V);
8281 if (!U) return Align;
8282
8283 switch (getOpcode(U)) {
8284 default: break;
8285 case Instruction::BitCast:
8286 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8287 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008288 // If all indexes are zero, it is just the alignment of the base pointer.
8289 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00008290 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00008291 if (!isa<Constant>(*i) ||
8292 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008293 AllZeroOperands = false;
8294 break;
8295 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008296
8297 if (AllZeroOperands) {
8298 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008299 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008300 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008301 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008302 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008303 }
8304
8305 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8306 // If there is a large requested alignment and we can, bump up the alignment
8307 // of the global.
8308 if (!GV->isDeclaration()) {
8309 GV->setAlignment(PrefAlign);
8310 Align = PrefAlign;
8311 }
8312 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8313 // If there is a requested alignment and if this is an alloca, round up. We
8314 // don't do this for malloc, because some systems can't respect the request.
8315 if (isa<AllocaInst>(AI)) {
8316 AI->setAlignment(PrefAlign);
8317 Align = PrefAlign;
8318 }
8319 }
8320
8321 return Align;
8322}
8323
8324/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8325/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8326/// and it is more than the alignment of the ultimate object, see if we can
8327/// increase the alignment of the ultimate object, making this check succeed.
8328unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8329 unsigned PrefAlign) {
8330 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8331 sizeof(PrefAlign) * CHAR_BIT;
8332 APInt Mask = APInt::getAllOnesValue(BitWidth);
8333 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8334 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8335 unsigned TrailZ = KnownZero.countTrailingOnes();
8336 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8337
8338 if (PrefAlign > Align)
8339 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8340
8341 // We don't need to make any adjustment.
8342 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008343}
8344
Chris Lattnerf497b022008-01-13 23:50:23 +00008345Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008346 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8347 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008348 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8349 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8350
8351 if (CopyAlign < MinAlign) {
8352 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8353 return MI;
8354 }
8355
8356 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8357 // load/store.
8358 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8359 if (MemOpLength == 0) return 0;
8360
Chris Lattner37ac6082008-01-14 00:28:35 +00008361 // Source and destination pointer types are always "i8*" for intrinsic. See
8362 // if the size is something we can handle with a single primitive load/store.
8363 // A single load+store correctly handles overlapping memory in the memmove
8364 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008365 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008366 if (Size == 0) return MI; // Delete this mem transfer.
8367
8368 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008369 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008370
Chris Lattner37ac6082008-01-14 00:28:35 +00008371 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008372 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008373
8374 // Memcpy forces the use of i8* for the source and destination. That means
8375 // that if you're using memcpy to move one double around, you'll get a cast
8376 // from double* to i8*. We'd much rather use a double load+store rather than
8377 // an i64 load+store, here because this improves the odds that the source or
8378 // dest address will be promotable. See if we can find a better type than the
8379 // integer datatype.
8380 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8381 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8382 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8383 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8384 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00008385 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00008386 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8387 if (STy->getNumElements() == 1)
8388 SrcETy = STy->getElementType(0);
8389 else
8390 break;
8391 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8392 if (ATy->getNumElements() == 1)
8393 SrcETy = ATy->getElementType();
8394 else
8395 break;
8396 } else
8397 break;
8398 }
8399
Dan Gohman8f8e2692008-05-23 01:52:21 +00008400 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00008401 NewPtrTy = PointerType::getUnqual(SrcETy);
8402 }
8403 }
8404
8405
Chris Lattnerf497b022008-01-13 23:50:23 +00008406 // If the memcpy/memmove provides better alignment info than we can
8407 // infer, use it.
8408 SrcAlign = std::max(SrcAlign, CopyAlign);
8409 DstAlign = std::max(DstAlign, CopyAlign);
8410
8411 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8412 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008413 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8414 InsertNewInstBefore(L, *MI);
8415 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8416
8417 // Set the size of the copy to 0, it will be deleted on the next iteration.
8418 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8419 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008420}
Chris Lattner3d69f462004-03-12 05:52:32 +00008421
Chris Lattner69ea9d22008-04-30 06:39:11 +00008422Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8423 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8424 if (MI->getAlignment()->getZExtValue() < Alignment) {
8425 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8426 return MI;
8427 }
8428
8429 // Extract the length and alignment and fill if they are constant.
8430 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8431 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8432 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8433 return 0;
8434 uint64_t Len = LenC->getZExtValue();
8435 Alignment = MI->getAlignment()->getZExtValue();
8436
8437 // If the length is zero, this is a no-op
8438 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8439
8440 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8441 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8442 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8443
8444 Value *Dest = MI->getDest();
8445 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8446
8447 // Alignment 0 is identity for alignment 1 for memset, but not store.
8448 if (Alignment == 0) Alignment = 1;
8449
8450 // Extract the fill value and store.
8451 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8452 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8453 Alignment), *MI);
8454
8455 // Set the size of the copy to 0, it will be deleted on the next iteration.
8456 MI->setLength(Constant::getNullValue(LenC->getType()));
8457 return MI;
8458 }
8459
8460 return 0;
8461}
8462
8463
Chris Lattner8b0ea312006-01-13 20:11:04 +00008464/// visitCallInst - CallInst simplification. This mostly only handles folding
8465/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8466/// the heavy lifting.
8467///
Chris Lattner9fe38862003-06-19 17:00:31 +00008468Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008469 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8470 if (!II) return visitCallSite(&CI);
8471
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008472 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8473 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008474 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008475 bool Changed = false;
8476
8477 // memmove/cpy/set of zero bytes is a noop.
8478 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8479 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8480
Chris Lattner35b9e482004-10-12 04:52:52 +00008481 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008482 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008483 // Replace the instruction with just byte operations. We would
8484 // transform other cases to loads/stores, but we don't know if
8485 // alignment is sufficient.
8486 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008487 }
8488
Chris Lattner35b9e482004-10-12 04:52:52 +00008489 // If we have a memmove and the source operation is a constant global,
8490 // then the source and dest pointers can't alias, so we can change this
8491 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008492 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008493 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8494 if (GVSrc->isConstant()) {
8495 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008496 Intrinsic::ID MemCpyID;
8497 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8498 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008499 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008500 MemCpyID = Intrinsic::memcpy_i64;
8501 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008502 Changed = true;
8503 }
Chris Lattnera935db82008-05-28 05:30:41 +00008504
8505 // memmove(x,x,size) -> noop.
8506 if (MMI->getSource() == MMI->getDest())
8507 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00008508 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008509
Chris Lattner95a959d2006-03-06 20:18:44 +00008510 // If we can determine a pointer alignment that is bigger than currently
8511 // set, update the alignment.
8512 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008513 if (Instruction *I = SimplifyMemTransfer(MI))
8514 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008515 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8516 if (Instruction *I = SimplifyMemSet(MSI))
8517 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008518 }
8519
Chris Lattner8b0ea312006-01-13 20:11:04 +00008520 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008521 } else {
8522 switch (II->getIntrinsicID()) {
8523 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008524 case Intrinsic::ppc_altivec_lvx:
8525 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008526 case Intrinsic::x86_sse_loadu_ps:
8527 case Intrinsic::x86_sse2_loadu_pd:
8528 case Intrinsic::x86_sse2_loadu_dq:
8529 // Turn PPC lvx -> load if the pointer is known aligned.
8530 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008531 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008532 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8533 PointerType::getUnqual(II->getType()),
8534 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008535 return new LoadInst(Ptr);
8536 }
8537 break;
8538 case Intrinsic::ppc_altivec_stvx:
8539 case Intrinsic::ppc_altivec_stvxl:
8540 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008541 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008542 const Type *OpPtrTy =
8543 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008544 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008545 return new StoreInst(II->getOperand(1), Ptr);
8546 }
8547 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008548 case Intrinsic::x86_sse_storeu_ps:
8549 case Intrinsic::x86_sse2_storeu_pd:
8550 case Intrinsic::x86_sse2_storeu_dq:
8551 case Intrinsic::x86_sse2_storel_dq:
8552 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008553 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008554 const Type *OpPtrTy =
8555 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008556 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008557 return new StoreInst(II->getOperand(2), Ptr);
8558 }
8559 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008560
8561 case Intrinsic::x86_sse_cvttss2si: {
8562 // These intrinsics only demands the 0th element of its input vector. If
8563 // we can simplify the input based on that, do so now.
8564 uint64_t UndefElts;
8565 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8566 UndefElts)) {
8567 II->setOperand(1, V);
8568 return II;
8569 }
8570 break;
8571 }
8572
Chris Lattnere2ed0572006-04-06 19:19:17 +00008573 case Intrinsic::ppc_altivec_vperm:
8574 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008575 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008576 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8577
8578 // Check that all of the elements are integer constants or undefs.
8579 bool AllEltsOk = true;
8580 for (unsigned i = 0; i != 16; ++i) {
8581 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8582 !isa<UndefValue>(Mask->getOperand(i))) {
8583 AllEltsOk = false;
8584 break;
8585 }
8586 }
8587
8588 if (AllEltsOk) {
8589 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008590 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8591 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008592 Value *Result = UndefValue::get(Op0->getType());
8593
8594 // Only extract each element once.
8595 Value *ExtractedElts[32];
8596 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8597
8598 for (unsigned i = 0; i != 16; ++i) {
8599 if (isa<UndefValue>(Mask->getOperand(i)))
8600 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008601 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008602 Idx &= 31; // Match the hardware behavior.
8603
8604 if (ExtractedElts[Idx] == 0) {
8605 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008606 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008607 InsertNewInstBefore(Elt, CI);
8608 ExtractedElts[Idx] = Elt;
8609 }
8610
8611 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008612 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8613 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008614 InsertNewInstBefore(cast<Instruction>(Result), CI);
8615 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008616 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008617 }
8618 }
8619 break;
8620
Chris Lattnera728ddc2006-01-13 21:28:09 +00008621 case Intrinsic::stackrestore: {
8622 // If the save is right next to the restore, remove the restore. This can
8623 // happen when variable allocas are DCE'd.
8624 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8625 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8626 BasicBlock::iterator BI = SS;
8627 if (&*++BI == II)
8628 return EraseInstFromFunction(CI);
8629 }
8630 }
8631
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008632 // Scan down this block to see if there is another stack restore in the
8633 // same block without an intervening call/alloca.
8634 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008635 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008636 bool CannotRemove = false;
8637 for (++BI; &*BI != TI; ++BI) {
8638 if (isa<AllocaInst>(BI)) {
8639 CannotRemove = true;
8640 break;
8641 }
8642 if (isa<CallInst>(BI)) {
8643 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008644 CannotRemove = true;
8645 break;
8646 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008647 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008648 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008649 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008650 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008651
8652 // If the stack restore is in a return/unwind block and if there are no
8653 // allocas or calls between the restore and the return, nuke the restore.
8654 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8655 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008656 break;
8657 }
8658 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008659 }
8660
Chris Lattner8b0ea312006-01-13 20:11:04 +00008661 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008662}
8663
8664// InvokeInst simplification
8665//
8666Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008667 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008668}
8669
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008670/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8671/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008672static bool isSafeToEliminateVarargsCast(const CallSite CS,
8673 const CastInst * const CI,
8674 const TargetData * const TD,
8675 const int ix) {
8676 if (!CI->isLosslessCast())
8677 return false;
8678
8679 // The size of ByVal arguments is derived from the type, so we
8680 // can't change to a type with a different size. If the size were
8681 // passed explicitly we could avoid this check.
8682 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8683 return true;
8684
8685 const Type* SrcTy =
8686 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8687 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8688 if (!SrcTy->isSized() || !DstTy->isSized())
8689 return false;
8690 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8691 return false;
8692 return true;
8693}
8694
Chris Lattnera44d8a22003-10-07 22:32:43 +00008695// visitCallSite - Improvements for call and invoke instructions.
8696//
8697Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008698 bool Changed = false;
8699
8700 // If the callee is a constexpr cast of a function, attempt to move the cast
8701 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008702 if (transformConstExprCastCall(CS)) return 0;
8703
Chris Lattner6c266db2003-10-07 22:54:13 +00008704 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008705
Chris Lattner08b22ec2005-05-13 07:09:09 +00008706 if (Function *CalleeF = dyn_cast<Function>(Callee))
8707 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8708 Instruction *OldCall = CS.getInstruction();
8709 // If the call and callee calling conventions don't match, this call must
8710 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008711 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008712 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8713 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008714 if (!OldCall->use_empty())
8715 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8716 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8717 return EraseInstFromFunction(*OldCall);
8718 return 0;
8719 }
8720
Chris Lattner17be6352004-10-18 02:59:09 +00008721 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8722 // This instruction is not reachable, just remove it. We insert a store to
8723 // undef so that we know that this code is not reachable, despite the fact
8724 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008725 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008726 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008727 CS.getInstruction());
8728
8729 if (!CS.getInstruction()->use_empty())
8730 CS.getInstruction()->
8731 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8732
8733 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8734 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008735 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8736 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008737 }
Chris Lattner17be6352004-10-18 02:59:09 +00008738 return EraseInstFromFunction(*CS.getInstruction());
8739 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008740
Duncan Sandscdb6d922007-09-17 10:26:40 +00008741 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8742 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8743 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8744 return transformCallThroughTrampoline(CS);
8745
Chris Lattner6c266db2003-10-07 22:54:13 +00008746 const PointerType *PTy = cast<PointerType>(Callee->getType());
8747 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8748 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00008749 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00008750 // See if we can optimize any arguments passed through the varargs area of
8751 // the call.
8752 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00008753 E = CS.arg_end(); I != E; ++I, ++ix) {
8754 CastInst *CI = dyn_cast<CastInst>(*I);
8755 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8756 *I = CI->getOperand(0);
8757 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00008758 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00008759 }
Chris Lattner6c266db2003-10-07 22:54:13 +00008760 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008761
Duncan Sandsf0c33542007-12-19 21:13:37 +00008762 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008763 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008764 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008765 Changed = true;
8766 }
8767
Chris Lattner6c266db2003-10-07 22:54:13 +00008768 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008769}
8770
Chris Lattner9fe38862003-06-19 17:00:31 +00008771// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8772// attempt to move the cast to the arguments of the call/invoke.
8773//
8774bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8775 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8776 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008777 if (CE->getOpcode() != Instruction::BitCast ||
8778 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008779 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008780 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008781 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008782 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008783
8784 // Okay, this is a cast from a function to a different type. Unless doing so
8785 // would cause a type conversion of one of our arguments, change this call to
8786 // be a direct call with arguments casted to the appropriate types.
8787 //
8788 const FunctionType *FT = Callee->getFunctionType();
8789 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008790 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00008791
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008792 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00008793 return false; // TODO: Handle multiple return values.
8794
Chris Lattnerf78616b2004-01-14 06:06:08 +00008795 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008796 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00008797 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008798 // Conversion is ok if changing from one pointer type to another or from
8799 // a pointer to an integer of the same size.
8800 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8801 isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType()))
Chris Lattnerec479922007-01-06 02:09:32 +00008802 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008803
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008804 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008805 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008806 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008807 return false; // Cannot transform this return value.
8808
Chris Lattner58d74912008-03-12 17:45:29 +00008809 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8810 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008811 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00008812 return false; // Attribute not compatible with transformed value.
8813 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008814
Chris Lattnerf78616b2004-01-14 06:06:08 +00008815 // If the callsite is an invoke instruction, and the return value is used by
8816 // a PHI node in a successor, we cannot change the return type of the call
8817 // because there is no place to put the cast instruction (without breaking
8818 // the critical edge). Bail out in this case.
8819 if (!Caller->use_empty())
8820 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8821 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8822 UI != E; ++UI)
8823 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8824 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008825 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008826 return false;
8827 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008828
8829 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8830 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008831
Chris Lattner9fe38862003-06-19 17:00:31 +00008832 CallSite::arg_iterator AI = CS.arg_begin();
8833 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8834 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008835 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008836
8837 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008838 return false; // Cannot transform this parameter value.
8839
Chris Lattner58d74912008-03-12 17:45:29 +00008840 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8841 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008842
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008843 // Converting from one pointer type to another or between a pointer and an
8844 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00008845 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008846 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8847 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00008848 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008849 }
8850
8851 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008852 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008853 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008854
Chris Lattner58d74912008-03-12 17:45:29 +00008855 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8856 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008857 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008858 // won't be dropping them. Check that these extra arguments have attributes
8859 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008860 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8861 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008862 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008863 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008864 if (PAttrs & ParamAttr::VarArgsIncompatible)
8865 return false;
8866 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008867
Chris Lattner9fe38862003-06-19 17:00:31 +00008868 // Okay, we decided that this is a safe thing to do: go ahead and start
8869 // inserting cast instructions as necessary...
8870 std::vector<Value*> Args;
8871 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008872 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008873 attrVec.reserve(NumCommonArgs);
8874
8875 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008876 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008877
8878 // If the return value is not being used, the type may not be compatible
8879 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008880 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008881
8882 // Add the new return attributes.
8883 if (RAttrs)
8884 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008885
8886 AI = CS.arg_begin();
8887 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8888 const Type *ParamTy = FT->getParamType(i);
8889 if ((*AI)->getType() == ParamTy) {
8890 Args.push_back(*AI);
8891 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008892 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008893 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008894 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008895 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008896 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008897
8898 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008899 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008900 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008901 }
8902
8903 // If the function takes more arguments than the call was taking, add them
8904 // now...
8905 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8906 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8907
8908 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008909 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008910 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008911 cerr << "WARNING: While resolving call to function '"
8912 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008913 } else {
8914 // Add all of the arguments in their promoted form to the arg list...
8915 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8916 const Type *PTy = getPromotedType((*AI)->getType());
8917 if (PTy != (*AI)->getType()) {
8918 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008919 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8920 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008921 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008922 InsertNewInstBefore(Cast, *Caller);
8923 Args.push_back(Cast);
8924 } else {
8925 Args.push_back(*AI);
8926 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008927
Duncan Sandse1e520f2008-01-13 08:02:44 +00008928 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008929 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00008930 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8931 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008932 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008933 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008934
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008935 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008936 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008937
Chris Lattner58d74912008-03-12 17:45:29 +00008938 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008939
Chris Lattner9fe38862003-06-19 17:00:31 +00008940 Instruction *NC;
8941 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00008942 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008943 Args.begin(), Args.end(),
8944 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008945 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008946 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008947 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00008948 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
8949 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008950 CallInst *CI = cast<CallInst>(Caller);
8951 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008952 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008953 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008954 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008955 }
8956
Chris Lattner6934a042007-02-11 01:23:03 +00008957 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008958 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008959 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008960 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008961 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008962 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008963 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008964
8965 // If this is an invoke instruction, we should insert it after the first
8966 // non-phi, instruction in the normal successor block.
8967 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00008968 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00008969 InsertNewInstBefore(NC, *I);
8970 } else {
8971 // Otherwise, it's a call, just insert cast right after the call instr
8972 InsertNewInstBefore(NC, *Caller);
8973 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008974 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008975 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008976 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008977 }
8978 }
8979
8980 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8981 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008982 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008983 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008984 return true;
8985}
8986
Duncan Sandscdb6d922007-09-17 10:26:40 +00008987// transformCallThroughTrampoline - Turn a call to a function created by the
8988// init_trampoline intrinsic into a direct call to the underlying function.
8989//
8990Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8991 Value *Callee = CS.getCalledValue();
8992 const PointerType *PTy = cast<PointerType>(Callee->getType());
8993 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00008994 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008995
8996 // If the call already has the 'nest' attribute somewhere then give up -
8997 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00008998 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008999 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009000
9001 IntrinsicInst *Tramp =
9002 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9003
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009004 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009005 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9006 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9007
Chris Lattner58d74912008-03-12 17:45:29 +00009008 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9009 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009010 unsigned NestIdx = 1;
9011 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009012 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009013
9014 // Look for a parameter marked with the 'nest' attribute.
9015 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9016 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009017 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009018 // Record the parameter type and any other attributes.
9019 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009020 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009021 break;
9022 }
9023
9024 if (NestTy) {
9025 Instruction *Caller = CS.getInstruction();
9026 std::vector<Value*> NewArgs;
9027 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9028
Chris Lattner58d74912008-03-12 17:45:29 +00009029 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9030 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009031
Duncan Sandscdb6d922007-09-17 10:26:40 +00009032 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009033 // mean appending it. Likewise for attributes.
9034
9035 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009036 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9037 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009038
Duncan Sandscdb6d922007-09-17 10:26:40 +00009039 {
9040 unsigned Idx = 1;
9041 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9042 do {
9043 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009044 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009045 Value *NestVal = Tramp->getOperand(3);
9046 if (NestVal->getType() != NestTy)
9047 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9048 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009049 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009050 }
9051
9052 if (I == E)
9053 break;
9054
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009055 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009056 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009057 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009058 NewAttrs.push_back
9059 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009060
9061 ++Idx, ++I;
9062 } while (1);
9063 }
9064
9065 // The trampoline may have been bitcast to a bogus type (FTy).
9066 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009067 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009068
Duncan Sandscdb6d922007-09-17 10:26:40 +00009069 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009070 NewTypes.reserve(FTy->getNumParams()+1);
9071
Duncan Sandscdb6d922007-09-17 10:26:40 +00009072 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009073 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009074 {
9075 unsigned Idx = 1;
9076 FunctionType::param_iterator I = FTy->param_begin(),
9077 E = FTy->param_end();
9078
9079 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009080 if (Idx == NestIdx)
9081 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009082 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009083
9084 if (I == E)
9085 break;
9086
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009087 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009088 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009089
9090 ++Idx, ++I;
9091 } while (1);
9092 }
9093
9094 // Replace the trampoline call with a direct call. Let the generic
9095 // code sort out any function type mismatches.
9096 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009097 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009098 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9099 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009100 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009101
9102 Instruction *NewCaller;
9103 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009104 NewCaller = InvokeInst::Create(NewCallee,
9105 II->getNormalDest(), II->getUnwindDest(),
9106 NewArgs.begin(), NewArgs.end(),
9107 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009108 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009109 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009110 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009111 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9112 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009113 if (cast<CallInst>(Caller)->isTailCall())
9114 cast<CallInst>(NewCaller)->setTailCall();
9115 cast<CallInst>(NewCaller)->
9116 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009117 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009118 }
9119 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9120 Caller->replaceAllUsesWith(NewCaller);
9121 Caller->eraseFromParent();
9122 RemoveFromWorkList(Caller);
9123 return 0;
9124 }
9125 }
9126
9127 // Replace the trampoline call with a direct call. Since there is no 'nest'
9128 // parameter, there is no need to adjust the argument list. Let the generic
9129 // code sort out any function type mismatches.
9130 Constant *NewCallee =
9131 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9132 CS.setCalledFunction(NewCallee);
9133 return CS.getInstruction();
9134}
9135
Chris Lattner7da52b22006-11-01 04:51:18 +00009136/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9137/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9138/// and a single binop.
9139Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9140 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009141 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9142 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009143 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009144 Value *LHSVal = FirstInst->getOperand(0);
9145 Value *RHSVal = FirstInst->getOperand(1);
9146
9147 const Type *LHSType = LHSVal->getType();
9148 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009149
9150 // Scan to see if all operands are the same opcode, all have one use, and all
9151 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009152 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009153 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009154 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009155 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009156 // types or GEP's with different index types.
9157 I->getOperand(0)->getType() != LHSType ||
9158 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009159 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009160
9161 // If they are CmpInst instructions, check their predicates
9162 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9163 if (cast<CmpInst>(I)->getPredicate() !=
9164 cast<CmpInst>(FirstInst)->getPredicate())
9165 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009166
9167 // Keep track of which operand needs a phi node.
9168 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9169 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009170 }
9171
Chris Lattner53738a42006-11-08 19:42:28 +00009172 // Otherwise, this is safe to transform, determine if it is profitable.
9173
9174 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9175 // Indexes are often folded into load/store instructions, so we don't want to
9176 // hide them behind a phi.
9177 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9178 return 0;
9179
Chris Lattner7da52b22006-11-01 04:51:18 +00009180 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009181 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009182 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009183 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009184 NewLHS = PHINode::Create(LHSType,
9185 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009186 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9187 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009188 InsertNewInstBefore(NewLHS, PN);
9189 LHSVal = NewLHS;
9190 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009191
9192 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009193 NewRHS = PHINode::Create(RHSType,
9194 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009195 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9196 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009197 InsertNewInstBefore(NewRHS, PN);
9198 RHSVal = NewRHS;
9199 }
9200
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009201 // Add all operands to the new PHIs.
9202 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9203 if (NewLHS) {
9204 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9205 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9206 }
9207 if (NewRHS) {
9208 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9209 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9210 }
9211 }
9212
Chris Lattner7da52b22006-11-01 04:51:18 +00009213 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009214 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009215 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009216 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009217 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009218 else {
9219 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009220 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009221 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009222}
9223
Chris Lattner76c73142006-11-01 07:13:54 +00009224/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9225/// of the block that defines it. This means that it must be obvious the value
9226/// of the load is not changed from the point of the load to the end of the
9227/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009228///
9229/// Finally, it is safe, but not profitable, to sink a load targetting a
9230/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9231/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009232static bool isSafeToSinkLoad(LoadInst *L) {
9233 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9234
9235 for (++BBI; BBI != E; ++BBI)
9236 if (BBI->mayWriteToMemory())
9237 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009238
9239 // Check for non-address taken alloca. If not address-taken already, it isn't
9240 // profitable to do this xform.
9241 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9242 bool isAddressTaken = false;
9243 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9244 UI != E; ++UI) {
9245 if (isa<LoadInst>(UI)) continue;
9246 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9247 // If storing TO the alloca, then the address isn't taken.
9248 if (SI->getOperand(1) == AI) continue;
9249 }
9250 isAddressTaken = true;
9251 break;
9252 }
9253
9254 if (!isAddressTaken)
9255 return false;
9256 }
9257
Chris Lattner76c73142006-11-01 07:13:54 +00009258 return true;
9259}
9260
Chris Lattner9fe38862003-06-19 17:00:31 +00009261
Chris Lattnerbac32862004-11-14 19:13:23 +00009262// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9263// operator and they all are only used by the PHI, PHI together their
9264// inputs, and do the operation once, to the result of the PHI.
9265Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9266 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9267
9268 // Scan the instruction, looking for input operations that can be folded away.
9269 // If all input operands to the phi are the same instruction (e.g. a cast from
9270 // the same type or "+42") we can pull the operation through the PHI, reducing
9271 // code size and simplifying code.
9272 Constant *ConstantOp = 0;
9273 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009274 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009275 if (isa<CastInst>(FirstInst)) {
9276 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009277 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009278 // Can fold binop, compare or shift here if the RHS is a constant,
9279 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009280 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009281 if (ConstantOp == 0)
9282 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009283 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9284 isVolatile = LI->isVolatile();
9285 // We can't sink the load if the loaded value could be modified between the
9286 // load and the PHI.
9287 if (LI->getParent() != PN.getIncomingBlock(0) ||
9288 !isSafeToSinkLoad(LI))
9289 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009290 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009291 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009292 return FoldPHIArgBinOpIntoPHI(PN);
9293 // Can't handle general GEPs yet.
9294 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009295 } else {
9296 return 0; // Cannot fold this operation.
9297 }
9298
9299 // Check to see if all arguments are the same operation.
9300 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9301 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9302 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009303 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009304 return 0;
9305 if (CastSrcTy) {
9306 if (I->getOperand(0)->getType() != CastSrcTy)
9307 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009308 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009309 // We can't sink the load if the loaded value could be modified between
9310 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009311 if (LI->isVolatile() != isVolatile ||
9312 LI->getParent() != PN.getIncomingBlock(i) ||
9313 !isSafeToSinkLoad(LI))
9314 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009315
9316 // If the PHI is volatile and its block has multiple successors, sinking
9317 // it would remove a load of the volatile value from the path through the
9318 // other successor.
9319 if (isVolatile &&
9320 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9321 return 0;
9322
9323
Chris Lattnerbac32862004-11-14 19:13:23 +00009324 } else if (I->getOperand(1) != ConstantOp) {
9325 return 0;
9326 }
9327 }
9328
9329 // Okay, they are all the same operation. Create a new PHI node of the
9330 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009331 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9332 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009333 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009334
9335 Value *InVal = FirstInst->getOperand(0);
9336 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009337
9338 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009339 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9340 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9341 if (NewInVal != InVal)
9342 InVal = 0;
9343 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9344 }
9345
9346 Value *PhiVal;
9347 if (InVal) {
9348 // The new PHI unions all of the same values together. This is really
9349 // common, so we handle it intelligently here for compile-time speed.
9350 PhiVal = InVal;
9351 delete NewPN;
9352 } else {
9353 InsertNewInstBefore(NewPN, PN);
9354 PhiVal = NewPN;
9355 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009356
Chris Lattnerbac32862004-11-14 19:13:23 +00009357 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009358 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009359 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009360 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009361 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009362 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009363 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009364 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009365 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9366
9367 // If this was a volatile load that we are merging, make sure to loop through
9368 // and mark all the input loads as non-volatile. If we don't do this, we will
9369 // insert a new volatile load and the old ones will not be deletable.
9370 if (isVolatile)
9371 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9372 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9373
9374 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009375}
Chris Lattnera1be5662002-05-02 17:06:02 +00009376
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009377/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9378/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009379static bool DeadPHICycle(PHINode *PN,
9380 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009381 if (PN->use_empty()) return true;
9382 if (!PN->hasOneUse()) return false;
9383
9384 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009385 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009386 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009387
9388 // Don't scan crazily complex things.
9389 if (PotentiallyDeadPHIs.size() == 16)
9390 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009391
9392 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9393 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009394
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009395 return false;
9396}
9397
Chris Lattnercf5008a2007-11-06 21:52:06 +00009398/// PHIsEqualValue - Return true if this phi node is always equal to
9399/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9400/// z = some value; x = phi (y, z); y = phi (x, z)
9401static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9402 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9403 // See if we already saw this PHI node.
9404 if (!ValueEqualPHIs.insert(PN))
9405 return true;
9406
9407 // Don't scan crazily complex things.
9408 if (ValueEqualPHIs.size() == 16)
9409 return false;
9410
9411 // Scan the operands to see if they are either phi nodes or are equal to
9412 // the value.
9413 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9414 Value *Op = PN->getIncomingValue(i);
9415 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9416 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9417 return false;
9418 } else if (Op != NonPhiInVal)
9419 return false;
9420 }
9421
9422 return true;
9423}
9424
9425
Chris Lattner473945d2002-05-06 18:06:38 +00009426// PHINode simplification
9427//
Chris Lattner7e708292002-06-25 16:13:24 +00009428Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009429 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009430 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009431
Owen Anderson7e057142006-07-10 22:03:18 +00009432 if (Value *V = PN.hasConstantValue())
9433 return ReplaceInstUsesWith(PN, V);
9434
Owen Anderson7e057142006-07-10 22:03:18 +00009435 // If all PHI operands are the same operation, pull them through the PHI,
9436 // reducing code size.
9437 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9438 PN.getIncomingValue(0)->hasOneUse())
9439 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9440 return Result;
9441
9442 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9443 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9444 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009445 if (PN.hasOneUse()) {
9446 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9447 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009448 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009449 PotentiallyDeadPHIs.insert(&PN);
9450 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9451 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9452 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009453
9454 // If this phi has a single use, and if that use just computes a value for
9455 // the next iteration of a loop, delete the phi. This occurs with unused
9456 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9457 // common case here is good because the only other things that catch this
9458 // are induction variable analysis (sometimes) and ADCE, which is only run
9459 // late.
9460 if (PHIUser->hasOneUse() &&
9461 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9462 PHIUser->use_back() == &PN) {
9463 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9464 }
9465 }
Owen Anderson7e057142006-07-10 22:03:18 +00009466
Chris Lattnercf5008a2007-11-06 21:52:06 +00009467 // We sometimes end up with phi cycles that non-obviously end up being the
9468 // same value, for example:
9469 // z = some value; x = phi (y, z); y = phi (x, z)
9470 // where the phi nodes don't necessarily need to be in the same block. Do a
9471 // quick check to see if the PHI node only contains a single non-phi value, if
9472 // so, scan to see if the phi cycle is actually equal to that value.
9473 {
9474 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9475 // Scan for the first non-phi operand.
9476 while (InValNo != NumOperandVals &&
9477 isa<PHINode>(PN.getIncomingValue(InValNo)))
9478 ++InValNo;
9479
9480 if (InValNo != NumOperandVals) {
9481 Value *NonPhiInVal = PN.getOperand(InValNo);
9482
9483 // Scan the rest of the operands to see if there are any conflicts, if so
9484 // there is no need to recursively scan other phis.
9485 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9486 Value *OpVal = PN.getIncomingValue(InValNo);
9487 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9488 break;
9489 }
9490
9491 // If we scanned over all operands, then we have one unique value plus
9492 // phi values. Scan PHI nodes to see if they all merge in each other or
9493 // the value.
9494 if (InValNo == NumOperandVals) {
9495 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9496 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9497 return ReplaceInstUsesWith(PN, NonPhiInVal);
9498 }
9499 }
9500 }
Chris Lattner60921c92003-12-19 05:58:40 +00009501 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009502}
9503
Reid Spencer17212df2006-12-12 09:18:51 +00009504static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9505 Instruction *InsertPoint,
9506 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009507 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9508 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009509 // We must cast correctly to the pointer type. Ensure that we
9510 // sign extend the integer value if it is smaller as this is
9511 // used for address computation.
9512 Instruction::CastOps opcode =
9513 (VTySize < PtrSize ? Instruction::SExt :
9514 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9515 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009516}
9517
Chris Lattnera1be5662002-05-02 17:06:02 +00009518
Chris Lattner7e708292002-06-25 16:13:24 +00009519Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009520 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009521 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009522 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009523 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009524 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009525
Chris Lattnere87597f2004-10-16 18:11:37 +00009526 if (isa<UndefValue>(GEP.getOperand(0)))
9527 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9528
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009529 bool HasZeroPointerIndex = false;
9530 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9531 HasZeroPointerIndex = C->isNullValue();
9532
9533 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009534 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009535
Chris Lattner28977af2004-04-05 01:30:19 +00009536 // Eliminate unneeded casts for indices.
9537 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009538
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009539 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009540 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9541 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009542 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009543 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009544 if (CI->getOpcode() == Instruction::ZExt ||
9545 CI->getOpcode() == Instruction::SExt) {
9546 const Type *SrcTy = CI->getOperand(0)->getType();
9547 // We can eliminate a cast from i32 to i64 iff the target
9548 // is a 32-bit pointer target.
9549 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9550 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +00009551 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +00009552 }
9553 }
9554 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009555 // If we are using a wider index than needed for this platform, shrink it
9556 // to what we need. If the incoming value needs a cast instruction,
9557 // insert it. This explicit cast can make subsequent optimizations more
9558 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +00009559 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009560 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009561 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009562 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +00009563 MadeChange = true;
9564 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009565 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9566 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009567 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009568 MadeChange = true;
9569 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009570 }
Chris Lattner28977af2004-04-05 01:30:19 +00009571 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009572 }
Chris Lattner28977af2004-04-05 01:30:19 +00009573 if (MadeChange) return &GEP;
9574
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009575 // If this GEP instruction doesn't move the pointer, and if the input operand
9576 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9577 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009578 if (GEP.hasAllZeroIndices()) {
9579 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9580 // If the bitcast is of an allocation, and the allocation will be
9581 // converted to match the type of the cast, don't touch this.
9582 if (isa<AllocationInst>(BCI->getOperand(0))) {
9583 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009584 if (Instruction *I = visitBitCast(*BCI)) {
9585 if (I != BCI) {
9586 I->takeName(BCI);
9587 BCI->getParent()->getInstList().insert(BCI, I);
9588 ReplaceInstUsesWith(*BCI, I);
9589 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009590 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009591 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009592 }
9593 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9594 }
9595 }
9596
Chris Lattner90ac28c2002-08-02 19:29:35 +00009597 // Combine Indices - If the source pointer to this getelementptr instruction
9598 // is a getelementptr instruction, combine the indices of the two
9599 // getelementptr instructions into a single instruction.
9600 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009601 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009602 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009603 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009604
9605 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009606 // Note that if our source is a gep chain itself that we wait for that
9607 // chain to be resolved before we perform this transformation. This
9608 // avoids us creating a TON of code in some cases.
9609 //
9610 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9611 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9612 return 0; // Wait until our source is folded to completion.
9613
Chris Lattner72588fc2007-02-15 22:48:32 +00009614 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009615
9616 // Find out whether the last index in the source GEP is a sequential idx.
9617 bool EndsWithSequential = false;
9618 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9619 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009620 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009621
Chris Lattner90ac28c2002-08-02 19:29:35 +00009622 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009623 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009624 // Replace: gep (gep %P, long B), long A, ...
9625 // With: T = long A+B; gep %P, T, ...
9626 //
Chris Lattner620ce142004-05-07 22:09:22 +00009627 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009628 if (SO1 == Constant::getNullValue(SO1->getType())) {
9629 Sum = GO1;
9630 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9631 Sum = SO1;
9632 } else {
9633 // If they aren't the same type, convert both to an integer of the
9634 // target's pointer size.
9635 if (SO1->getType() != GO1->getType()) {
9636 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009637 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009638 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009639 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009640 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009641 unsigned PS = TD->getPointerSizeInBits();
9642 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009643 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009644 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009645
Duncan Sands514ab342007-11-01 20:53:16 +00009646 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009647 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009648 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009649 } else {
9650 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009651 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9652 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009653 }
9654 }
9655 }
Chris Lattner620ce142004-05-07 22:09:22 +00009656 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9657 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9658 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009659 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +00009660 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009661 }
Chris Lattner28977af2004-04-05 01:30:19 +00009662 }
Chris Lattner620ce142004-05-07 22:09:22 +00009663
9664 // Recycle the GEP we already have if possible.
9665 if (SrcGEPOperands.size() == 2) {
9666 GEP.setOperand(0, SrcGEPOperands[0]);
9667 GEP.setOperand(1, Sum);
9668 return &GEP;
9669 } else {
9670 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9671 SrcGEPOperands.end()-1);
9672 Indices.push_back(Sum);
9673 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9674 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009675 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009676 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009677 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009678 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009679 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9680 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009681 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9682 }
9683
9684 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009685 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9686 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009687
Chris Lattner620ce142004-05-07 22:09:22 +00009688 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009689 // GEP of global variable. If all of the indices for this GEP are
9690 // constants, we can promote this to a constexpr instead of an instruction.
9691
9692 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009693 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009694 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9695 for (; I != E && isa<Constant>(*I); ++I)
9696 Indices.push_back(cast<Constant>(*I));
9697
9698 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009699 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9700 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009701
9702 // Replace all uses of the GEP with the new constexpr...
9703 return ReplaceInstUsesWith(GEP, CE);
9704 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009705 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009706 if (!isa<PointerType>(X->getType())) {
9707 // Not interesting. Source pointer must be a cast from pointer.
9708 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009709 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9710 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009711 //
9712 // This occurs when the program declares an array extern like "int X[];"
9713 //
9714 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9715 const PointerType *XTy = cast<PointerType>(X->getType());
9716 if (const ArrayType *XATy =
9717 dyn_cast<ArrayType>(XTy->getElementType()))
9718 if (const ArrayType *CATy =
9719 dyn_cast<ArrayType>(CPTy->getElementType()))
9720 if (CATy->getElementType() == XATy->getElementType()) {
9721 // At this point, we know that the cast source type is a pointer
9722 // to an array of the same type as the destination pointer
9723 // array. Because the array type is never stepped over (there
9724 // is a leading zero) we can fold the cast into this GEP.
9725 GEP.setOperand(0, X);
9726 return &GEP;
9727 }
9728 } else if (GEP.getNumOperands() == 2) {
9729 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009730 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9731 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009732 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9733 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9734 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009735 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9736 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009737 Value *Idx[2];
9738 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9739 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009740 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009741 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009742 // V and GEP are both pointer types --> BitCast
9743 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009744 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009745
9746 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009747 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009748 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009749 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009750
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009751 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009752 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009753 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009754
9755 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9756 // allow either a mul, shift, or constant here.
9757 Value *NewIdx = 0;
9758 ConstantInt *Scale = 0;
9759 if (ArrayEltSize == 1) {
9760 NewIdx = GEP.getOperand(1);
9761 Scale = ConstantInt::get(NewIdx->getType(), 1);
9762 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009763 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009764 Scale = CI;
9765 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9766 if (Inst->getOpcode() == Instruction::Shl &&
9767 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009768 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9769 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9770 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009771 NewIdx = Inst->getOperand(0);
9772 } else if (Inst->getOpcode() == Instruction::Mul &&
9773 isa<ConstantInt>(Inst->getOperand(1))) {
9774 Scale = cast<ConstantInt>(Inst->getOperand(1));
9775 NewIdx = Inst->getOperand(0);
9776 }
9777 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009778
Chris Lattner7835cdd2005-09-13 18:36:04 +00009779 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009780 // out, perform the transformation. Note, we don't know whether Scale is
9781 // signed or not. We'll use unsigned version of division/modulo
9782 // operation after making sure Scale doesn't have the sign bit set.
9783 if (Scale && Scale->getSExtValue() >= 0LL &&
9784 Scale->getZExtValue() % ArrayEltSize == 0) {
9785 Scale = ConstantInt::get(Scale->getType(),
9786 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009787 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009788 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009789 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009790 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00009791 NewIdx = InsertNewInstBefore(Sc, GEP);
9792 }
9793
9794 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009795 Value *Idx[2];
9796 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9797 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009798 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009799 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009800 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9801 // The NewGEP must be pointer typed, so must the old one -> BitCast
9802 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009803 }
9804 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009805 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009806 }
9807
Chris Lattner8a2a3112001-12-14 16:52:21 +00009808 return 0;
9809}
9810
Chris Lattner0864acf2002-11-04 16:18:53 +00009811Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9812 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009813 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009814 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9815 const Type *NewTy =
9816 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009817 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009818
9819 // Create and insert the replacement instruction...
9820 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009821 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009822 else {
9823 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009824 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009825 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009826
9827 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009828
Chris Lattner0864acf2002-11-04 16:18:53 +00009829 // Scan to the end of the allocation instructions, to skip over a block of
9830 // allocas if possible...
9831 //
9832 BasicBlock::iterator It = New;
9833 while (isa<AllocationInst>(*It)) ++It;
9834
9835 // Now that I is pointing to the first non-allocation-inst in the block,
9836 // insert our getelementptr instruction...
9837 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009838 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009839 Value *Idx[2];
9840 Idx[0] = NullIdx;
9841 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +00009842 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9843 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009844
9845 // Now make everything use the getelementptr instead of the original
9846 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009847 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009848 } else if (isa<UndefValue>(AI.getArraySize())) {
9849 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009850 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009851 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009852
9853 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9854 // Note that we only do this for alloca's, because malloc should allocate and
9855 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009856 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009857 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009858 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9859
Chris Lattner0864acf2002-11-04 16:18:53 +00009860 return 0;
9861}
9862
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009863Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9864 Value *Op = FI.getOperand(0);
9865
Chris Lattner17be6352004-10-18 02:59:09 +00009866 // free undef -> unreachable.
9867 if (isa<UndefValue>(Op)) {
9868 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009869 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009870 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009871 return EraseInstFromFunction(FI);
9872 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009873
Chris Lattner6160e852004-02-28 04:57:37 +00009874 // If we have 'free null' delete the instruction. This can happen in stl code
9875 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009876 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009877 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009878
9879 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9880 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9881 FI.setOperand(0, CI->getOperand(0));
9882 return &FI;
9883 }
9884
9885 // Change free (gep X, 0,0,0,0) into free(X)
9886 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9887 if (GEPI->hasAllZeroIndices()) {
9888 AddToWorkList(GEPI);
9889 FI.setOperand(0, GEPI->getOperand(0));
9890 return &FI;
9891 }
9892 }
9893
9894 // Change free(malloc) into nothing, if the malloc has a single use.
9895 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9896 if (MI->hasOneUse()) {
9897 EraseInstFromFunction(FI);
9898 return EraseInstFromFunction(*MI);
9899 }
Chris Lattner6160e852004-02-28 04:57:37 +00009900
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009901 return 0;
9902}
9903
9904
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009905/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009906static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009907 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009908 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009909 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009910
Devang Patel99db6ad2007-10-18 19:52:32 +00009911 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9912 // Instead of loading constant c string, use corresponding integer value
9913 // directly if string length is small enough.
9914 const std::string &Str = CE->getOperand(0)->getStringValue();
9915 if (!Str.empty()) {
9916 unsigned len = Str.length();
9917 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9918 unsigned numBits = Ty->getPrimitiveSizeInBits();
9919 // Replace LI with immediate integer store.
9920 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009921 APInt StrVal(numBits, 0);
9922 APInt SingleChar(numBits, 0);
9923 if (TD->isLittleEndian()) {
9924 for (signed i = len-1; i >= 0; i--) {
9925 SingleChar = (uint64_t) Str[i];
9926 StrVal = (StrVal << 8) | SingleChar;
9927 }
9928 } else {
9929 for (unsigned i = 0; i < len; i++) {
9930 SingleChar = (uint64_t) Str[i];
9931 StrVal = (StrVal << 8) | SingleChar;
9932 }
9933 // Append NULL at the end.
9934 SingleChar = 0;
9935 StrVal = (StrVal << 8) | SingleChar;
9936 }
9937 Value *NL = ConstantInt::get(StrVal);
9938 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009939 }
9940 }
9941 }
9942
Chris Lattnerb89e0712004-07-13 01:49:43 +00009943 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009944 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009945 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009946
Reid Spencer42230162007-01-22 05:51:25 +00009947 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009948 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009949 // If the source is an array, the code below will not succeed. Check to
9950 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9951 // constants.
9952 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9953 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9954 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009955 Value *Idxs[2];
9956 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9957 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009958 SrcTy = cast<PointerType>(CastOp->getType());
9959 SrcPTy = SrcTy->getElementType();
9960 }
9961
Reid Spencer42230162007-01-22 05:51:25 +00009962 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009963 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009964 // Do not allow turning this into a load of an integer, which is then
9965 // casted to a pointer, this pessimizes pointer analysis a lot.
9966 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009967 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9968 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009969
Chris Lattnerf9527852005-01-31 04:50:46 +00009970 // Okay, we are casting from one integer or pointer type to another of
9971 // the same size. Instead of casting the pointer before the load, cast
9972 // the result of the loaded value.
9973 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9974 CI->getName(),
9975 LI.isVolatile()),LI);
9976 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009977 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009978 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009979 }
9980 }
9981 return 0;
9982}
9983
Chris Lattnerc10aced2004-09-19 18:43:46 +00009984/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009985/// from this value cannot trap. If it is not obviously safe to load from the
9986/// specified pointer, we do a quick local scan of the basic block containing
9987/// ScanFrom, to determine if the address is already accessed.
9988static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009989 // If it is an alloca it is always safe to load from.
9990 if (isa<AllocaInst>(V)) return true;
9991
Duncan Sands46318cd2007-09-19 10:25:38 +00009992 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009993 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009994 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009995 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009996
9997 // Otherwise, be a little bit agressive by scanning the local block where we
9998 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009999 // from/to. If so, the previous load or store would have already trapped,
10000 // so there is no harm doing an extra load (also, CSE will later eliminate
10001 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010002 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10003
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010004 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010005 --BBI;
10006
10007 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10008 if (LI->getOperand(0) == V) return true;
10009 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10010 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010011
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010012 }
Chris Lattner8a375202004-09-19 19:18:10 +000010013 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010014}
10015
Chris Lattner8d2e8882007-08-11 18:48:48 +000010016/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10017/// until we find the underlying object a pointer is referring to or something
10018/// we don't understand. Note that the returned pointer may be offset from the
10019/// input, because we ignore GEP indices.
10020static Value *GetUnderlyingObject(Value *Ptr) {
10021 while (1) {
10022 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10023 if (CE->getOpcode() == Instruction::BitCast ||
10024 CE->getOpcode() == Instruction::GetElementPtr)
10025 Ptr = CE->getOperand(0);
10026 else
10027 return Ptr;
10028 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10029 Ptr = BCI->getOperand(0);
10030 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10031 Ptr = GEP->getOperand(0);
10032 } else {
10033 return Ptr;
10034 }
10035 }
10036}
10037
Chris Lattner833b8a42003-06-26 05:06:25 +000010038Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10039 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010040
Dan Gohman9941f742007-07-20 16:34:21 +000010041 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010042 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10043 if (KnownAlign >
10044 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10045 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010046 LI.setAlignment(KnownAlign);
10047
Chris Lattner37366c12005-05-01 04:24:53 +000010048 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010049 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010050 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010051 return Res;
10052
10053 // None of the following transforms are legal for volatile loads.
10054 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010055
Chris Lattner62f254d2005-09-12 22:00:15 +000010056 if (&LI.getParent()->front() != &LI) {
10057 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010058 // If the instruction immediately before this is a store to the same
10059 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010060 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10061 if (SI->getOperand(1) == LI.getOperand(0))
10062 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010063 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10064 if (LIB->getOperand(0) == LI.getOperand(0))
10065 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010066 }
Chris Lattner37366c12005-05-01 04:24:53 +000010067
Christopher Lambb15147e2007-12-29 07:56:53 +000010068 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10069 const Value *GEPI0 = GEPI->getOperand(0);
10070 // TODO: Consider a target hook for valid address spaces for this xform.
10071 if (isa<ConstantPointerNull>(GEPI0) &&
10072 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010073 // Insert a new store to null instruction before the load to indicate
10074 // that this code is not reachable. We do this instead of inserting
10075 // an unreachable instruction directly because we cannot modify the
10076 // CFG.
10077 new StoreInst(UndefValue::get(LI.getType()),
10078 Constant::getNullValue(Op->getType()), &LI);
10079 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10080 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010081 }
Chris Lattner37366c12005-05-01 04:24:53 +000010082
Chris Lattnere87597f2004-10-16 18:11:37 +000010083 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010084 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010085 // TODO: Consider a target hook for valid address spaces for this xform.
10086 if (isa<UndefValue>(C) || (C->isNullValue() &&
10087 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010088 // Insert a new store to null instruction before the load to indicate that
10089 // this code is not reachable. We do this instead of inserting an
10090 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010091 new StoreInst(UndefValue::get(LI.getType()),
10092 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010093 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010094 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010095
Chris Lattnere87597f2004-10-16 18:11:37 +000010096 // Instcombine load (constant global) into the value loaded.
10097 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010098 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010099 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010100
Chris Lattnere87597f2004-10-16 18:11:37 +000010101 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010102 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010103 if (CE->getOpcode() == Instruction::GetElementPtr) {
10104 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010105 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010106 if (Constant *V =
10107 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010108 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010109 if (CE->getOperand(0)->isNullValue()) {
10110 // Insert a new store to null instruction before the load to indicate
10111 // that this code is not reachable. We do this instead of inserting
10112 // an unreachable instruction directly because we cannot modify the
10113 // CFG.
10114 new StoreInst(UndefValue::get(LI.getType()),
10115 Constant::getNullValue(Op->getType()), &LI);
10116 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10117 }
10118
Reid Spencer3da59db2006-11-27 01:05:10 +000010119 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010120 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010121 return Res;
10122 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010123 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010124 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010125
10126 // If this load comes from anywhere in a constant global, and if the global
10127 // is all undef or zero, we know what it loads.
10128 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10129 if (GV->isConstant() && GV->hasInitializer()) {
10130 if (GV->getInitializer()->isNullValue())
10131 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10132 else if (isa<UndefValue>(GV->getInitializer()))
10133 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10134 }
10135 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010136
Chris Lattner37366c12005-05-01 04:24:53 +000010137 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010138 // Change select and PHI nodes to select values instead of addresses: this
10139 // helps alias analysis out a lot, allows many others simplifications, and
10140 // exposes redundancy in the code.
10141 //
10142 // Note that we cannot do the transformation unless we know that the
10143 // introduced loads cannot trap! Something like this is valid as long as
10144 // the condition is always false: load (select bool %C, int* null, int* %G),
10145 // but it would not be valid if we transformed it to load from null
10146 // unconditionally.
10147 //
10148 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10149 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010150 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10151 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010152 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010153 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010154 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010155 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010156 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010157 }
10158
Chris Lattner684fe212004-09-23 15:46:00 +000010159 // load (select (cond, null, P)) -> load P
10160 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10161 if (C->isNullValue()) {
10162 LI.setOperand(0, SI->getOperand(2));
10163 return &LI;
10164 }
10165
10166 // load (select (cond, P, null)) -> load P
10167 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10168 if (C->isNullValue()) {
10169 LI.setOperand(0, SI->getOperand(1));
10170 return &LI;
10171 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010172 }
10173 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010174 return 0;
10175}
10176
Reid Spencer55af2b52007-01-19 21:20:31 +000010177/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010178/// when possible.
10179static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10180 User *CI = cast<User>(SI.getOperand(1));
10181 Value *CastOp = CI->getOperand(0);
10182
10183 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10184 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10185 const Type *SrcPTy = SrcTy->getElementType();
10186
Reid Spencer42230162007-01-22 05:51:25 +000010187 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010188 // If the source is an array, the code below will not succeed. Check to
10189 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10190 // constants.
10191 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10192 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10193 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010194 Value* Idxs[2];
10195 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10196 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010197 SrcTy = cast<PointerType>(CastOp->getType());
10198 SrcPTy = SrcTy->getElementType();
10199 }
10200
Reid Spencer67f827c2007-01-20 23:35:48 +000010201 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10202 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10203 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010204
10205 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010206 // the same size. Instead of casting the pointer before
10207 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010208 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010209 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010210 Instruction::CastOps opcode = Instruction::BitCast;
10211 const Type* CastSrcTy = SIOp0->getType();
10212 const Type* CastDstTy = SrcPTy;
10213 if (isa<PointerType>(CastDstTy)) {
10214 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010215 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010216 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010217 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010218 opcode = Instruction::PtrToInt;
10219 }
10220 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010221 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010222 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010223 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010224 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010225 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010226 return new StoreInst(NewCast, CastOp);
10227 }
10228 }
10229 }
10230 return 0;
10231}
10232
Chris Lattner2f503e62005-01-31 05:36:43 +000010233Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10234 Value *Val = SI.getOperand(0);
10235 Value *Ptr = SI.getOperand(1);
10236
10237 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010238 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010239 ++NumCombined;
10240 return 0;
10241 }
Chris Lattner836692d2007-01-15 06:51:56 +000010242
10243 // If the RHS is an alloca with a single use, zapify the store, making the
10244 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010245 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010246 if (isa<AllocaInst>(Ptr)) {
10247 EraseInstFromFunction(SI);
10248 ++NumCombined;
10249 return 0;
10250 }
10251
10252 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10253 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10254 GEP->getOperand(0)->hasOneUse()) {
10255 EraseInstFromFunction(SI);
10256 ++NumCombined;
10257 return 0;
10258 }
10259 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010260
Dan Gohman9941f742007-07-20 16:34:21 +000010261 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010262 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10263 if (KnownAlign >
10264 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10265 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010266 SI.setAlignment(KnownAlign);
10267
Chris Lattner9ca96412006-02-08 03:25:32 +000010268 // Do really simple DSE, to catch cases where there are several consequtive
10269 // stores to the same location, separated by a few arithmetic operations. This
10270 // situation often occurs with bitfield accesses.
10271 BasicBlock::iterator BBI = &SI;
10272 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10273 --ScanInsts) {
10274 --BBI;
10275
10276 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10277 // Prev store isn't volatile, and stores to the same location?
10278 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10279 ++NumDeadStore;
10280 ++BBI;
10281 EraseInstFromFunction(*PrevSI);
10282 continue;
10283 }
10284 break;
10285 }
10286
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010287 // If this is a load, we have to stop. However, if the loaded value is from
10288 // the pointer we're loading and is producing the pointer we're storing,
10289 // then *this* store is dead (X = load P; store X -> P).
10290 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010291 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010292 EraseInstFromFunction(SI);
10293 ++NumCombined;
10294 return 0;
10295 }
10296 // Otherwise, this is a load from some other location. Stores before it
10297 // may not be dead.
10298 break;
10299 }
10300
Chris Lattner9ca96412006-02-08 03:25:32 +000010301 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010302 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010303 break;
10304 }
10305
10306
10307 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010308
10309 // store X, null -> turns into 'unreachable' in SimplifyCFG
10310 if (isa<ConstantPointerNull>(Ptr)) {
10311 if (!isa<UndefValue>(Val)) {
10312 SI.setOperand(0, UndefValue::get(Val->getType()));
10313 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010314 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010315 ++NumCombined;
10316 }
10317 return 0; // Do not modify these!
10318 }
10319
10320 // store undef, Ptr -> noop
10321 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010322 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010323 ++NumCombined;
10324 return 0;
10325 }
10326
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010327 // If the pointer destination is a cast, see if we can fold the cast into the
10328 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010329 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010330 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10331 return Res;
10332 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010333 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010334 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10335 return Res;
10336
Chris Lattner408902b2005-09-12 23:23:25 +000010337
10338 // If this store is the last instruction in the basic block, and if the block
10339 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010340 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010341 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010342 if (BI->isUnconditional())
10343 if (SimplifyStoreAtEndOfBlock(SI))
10344 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010345
Chris Lattner2f503e62005-01-31 05:36:43 +000010346 return 0;
10347}
10348
Chris Lattner3284d1f2007-04-15 00:07:55 +000010349/// SimplifyStoreAtEndOfBlock - Turn things like:
10350/// if () { *P = v1; } else { *P = v2 }
10351/// into a phi node with a store in the successor.
10352///
Chris Lattner31755a02007-04-15 01:02:18 +000010353/// Simplify things like:
10354/// *P = v1; if () { *P = v2; }
10355/// into a phi node with a store in the successor.
10356///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010357bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10358 BasicBlock *StoreBB = SI.getParent();
10359
10360 // Check to see if the successor block has exactly two incoming edges. If
10361 // so, see if the other predecessor contains a store to the same location.
10362 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010363 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010364
10365 // Determine whether Dest has exactly two predecessors and, if so, compute
10366 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010367 pred_iterator PI = pred_begin(DestBB);
10368 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010369 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010370 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010371 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010372 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010373 return false;
10374
10375 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010376 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010377 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010378 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010379 }
Chris Lattner31755a02007-04-15 01:02:18 +000010380 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010381 return false;
10382
10383
Chris Lattner31755a02007-04-15 01:02:18 +000010384 // Verify that the other block ends in a branch and is not otherwise empty.
10385 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010386 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010387 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010388 return false;
10389
Chris Lattner31755a02007-04-15 01:02:18 +000010390 // If the other block ends in an unconditional branch, check for the 'if then
10391 // else' case. there is an instruction before the branch.
10392 StoreInst *OtherStore = 0;
10393 if (OtherBr->isUnconditional()) {
10394 // If this isn't a store, or isn't a store to the same location, bail out.
10395 --BBI;
10396 OtherStore = dyn_cast<StoreInst>(BBI);
10397 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10398 return false;
10399 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010400 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010401 // destinations is StoreBB, then we have the if/then case.
10402 if (OtherBr->getSuccessor(0) != StoreBB &&
10403 OtherBr->getSuccessor(1) != StoreBB)
10404 return false;
10405
10406 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010407 // if/then triangle. See if there is a store to the same ptr as SI that
10408 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010409 for (;; --BBI) {
10410 // Check to see if we find the matching store.
10411 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10412 if (OtherStore->getOperand(1) != SI.getOperand(1))
10413 return false;
10414 break;
10415 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010416 // If we find something that may be using the stored value, or if we run
10417 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010418 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10419 BBI == OtherBB->begin())
10420 return false;
10421 }
10422
10423 // In order to eliminate the store in OtherBr, we have to
10424 // make sure nothing reads the stored value in StoreBB.
10425 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10426 // FIXME: This should really be AA driven.
10427 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10428 return false;
10429 }
10430 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010431
Chris Lattner31755a02007-04-15 01:02:18 +000010432 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010433 Value *MergedVal = OtherStore->getOperand(0);
10434 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010435 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010436 PN->reserveOperandSpace(2);
10437 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010438 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10439 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010440 }
10441
10442 // Advance to a place where it is safe to insert the new store and
10443 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000010444 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010445 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10446 OtherStore->isVolatile()), *BBI);
10447
10448 // Nuke the old stores.
10449 EraseInstFromFunction(SI);
10450 EraseInstFromFunction(*OtherStore);
10451 ++NumCombined;
10452 return true;
10453}
10454
Chris Lattner2f503e62005-01-31 05:36:43 +000010455
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010456Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10457 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010458 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010459 BasicBlock *TrueDest;
10460 BasicBlock *FalseDest;
10461 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10462 !isa<Constant>(X)) {
10463 // Swap Destinations and condition...
10464 BI.setCondition(X);
10465 BI.setSuccessor(0, FalseDest);
10466 BI.setSuccessor(1, TrueDest);
10467 return &BI;
10468 }
10469
Reid Spencere4d87aa2006-12-23 06:05:41 +000010470 // Cannonicalize fcmp_one -> fcmp_oeq
10471 FCmpInst::Predicate FPred; Value *Y;
10472 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10473 TrueDest, FalseDest)))
10474 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10475 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10476 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010477 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010478 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10479 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010480 // Swap Destinations and condition...
10481 BI.setCondition(NewSCC);
10482 BI.setSuccessor(0, FalseDest);
10483 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010484 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010485 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010486 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010487 return &BI;
10488 }
10489
10490 // Cannonicalize icmp_ne -> icmp_eq
10491 ICmpInst::Predicate IPred;
10492 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10493 TrueDest, FalseDest)))
10494 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10495 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10496 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10497 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010498 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010499 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10500 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010501 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010502 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010503 BI.setSuccessor(0, FalseDest);
10504 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010505 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010506 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010507 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010508 return &BI;
10509 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010510
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010511 return 0;
10512}
Chris Lattner0864acf2002-11-04 16:18:53 +000010513
Chris Lattner46238a62004-07-03 00:26:11 +000010514Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10515 Value *Cond = SI.getCondition();
10516 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10517 if (I->getOpcode() == Instruction::Add)
10518 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10519 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10520 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010521 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010522 AddRHS));
10523 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010524 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010525 return &SI;
10526 }
10527 }
10528 return 0;
10529}
10530
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010531// This is the recursive version of BuildSubAggregate. It takes a few different
10532// arguments. Idxs is the index within the nested struct From that we are
10533// looking at now (which is of type IndexedType). IdxSkip is the number of
10534// indices from Idxs that should be left out when inserting into the resulting
10535// struct. To is the result struct built so far, new insertvalue instructions
10536// build on that.
10537Value *InstCombiner::BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
10538 SmallVector<unsigned, 10> &Idxs,
10539 unsigned IdxSkip,
10540 Instruction &InsertBefore) {
10541 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
10542 if (STy) {
10543 // General case, the type indexed by Idxs is a struct
10544 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
10545 // Process each struct element recursively
10546 Idxs.push_back(i);
10547 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip, InsertBefore);
10548 Idxs.pop_back();
10549 }
10550 return To;
10551 } else {
10552 // Base case, the type indexed by SourceIdxs is not a struct
10553 // Load the value from the nested struct into the sub struct (and skip
10554 // IdxSkip indices when indexing the sub struct).
10555 Instruction *V = llvm::ExtractValueInst::Create(From, Idxs.begin(), Idxs.end(), "tmp");
10556 InsertNewInstBefore(V, InsertBefore);
10557 Instruction *Ins = llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip, Idxs.end(), "tmp");
10558 InsertNewInstBefore(Ins, InsertBefore);
10559 return Ins;
10560 }
10561}
10562
10563// This helper takes a nested struct and extracts a part of it (which is again a
10564// struct) into a new value. For example, given the struct:
10565// { a, { b, { c, d }, e } }
10566// and the indices "1, 1" this returns
10567// { c, d }.
10568//
10569// It does this by inserting an extractvalue and insertvalue for each element in
10570// the resulting struct, as opposed to just inserting a single struct. This
10571// allows for later folding of these individual extractvalue instructions with
10572// insertvalue instructions that fill the nested struct.
10573//
10574// Any inserted instructions are inserted before InsertBefore
10575Value *InstCombiner::BuildSubAggregate(Value *From, const unsigned *idx_begin, const unsigned *idx_end, Instruction &InsertBefore) {
10576 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(), idx_begin, idx_end);
10577 Value *To = UndefValue::get(IndexedType);
10578 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
10579 unsigned IdxSkip = Idxs.size();
10580
10581 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
10582}
10583
10584/// FindScalarValue - Given an aggregrate and an sequence of indices, see if the
10585/// scalar value indexed is already around as a register, for example if it were
10586/// inserted directly into the aggregrate.
10587Value *InstCombiner::FindScalarValue(Value *V, const unsigned *idx_begin,
10588 const unsigned *idx_end, Instruction &InsertBefore) {
10589 // Nothing to index? Just return V then (this is useful at the end of our
10590 // recursion)
10591 if (idx_begin == idx_end)
10592 return V;
10593 // We have indices, so V should have an indexable type
10594 assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType()))
10595 && "Not looking at a struct or array?");
10596 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
10597 && "Invalid indices for type?");
10598 const CompositeType *PTy = cast<CompositeType>(V->getType());
10599
10600 if (isa<UndefValue>(V))
10601 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
10602 idx_begin,
10603 idx_end));
10604 else if (isa<ConstantAggregateZero>(V))
10605 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
10606 idx_begin,
10607 idx_end));
10608 else if (Constant *C = dyn_cast<Constant>(V)) {
10609 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
10610 // Recursively process this constant
10611 return FindScalarValue(C->getOperand(*idx_begin), ++idx_begin, idx_end, InsertBefore);
10612 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
10613 // Loop the indices for the insertvalue instruction in parallel with the
10614 // requested indices
10615 const unsigned *req_idx = idx_begin;
10616 for (const unsigned *i = I->idx_begin(), *e = I->idx_end(); i != e; ++i, ++req_idx) {
10617 if (req_idx == idx_end)
10618 // The requested index is a part of a nested aggregate. Handle this
10619 // specially.
10620 return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
10621
10622 // This insert value inserts something else than what we are looking for.
10623 // See if the (aggregrate) value inserted into has the value we are
10624 // looking for, then.
10625 if (*req_idx != *i)
10626 return FindScalarValue(I->getAggregateOperand(), idx_begin, idx_end, InsertBefore);
10627 }
10628 // If we end up here, the indices of the insertvalue match with those
10629 // requested (though possibly only partially). Now we recursively look at
10630 // the inserted value, passing any remaining indices.
10631 return FindScalarValue(I->getInsertedValueOperand(), req_idx, idx_end, InsertBefore);
10632 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
10633 // If we're extracting a value from an aggregrate that was extracted from
10634 // something else, we can extract from that something else directly instead.
10635 // However, we will need to chain I's indices with the requested indices.
10636
10637 // Calculate the number of indices required
10638 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
10639 // Allocate some space to put the new indices in
10640 unsigned *new_begin = new unsigned[size];
10641 // Auto cleanup this array
10642 std::auto_ptr<unsigned> newptr(new_begin);
10643 // Start inserting at the beginning
10644 unsigned *new_end = new_begin;
10645 // Add indices from the extract value instruction
10646 for (const unsigned *i = I->idx_begin(), *e = I->idx_end(); i != e; ++i, ++new_end)
10647 *new_end = *i;
10648
10649 // Add requested indices
10650 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i, ++new_end)
10651 *new_end = *i;
10652
10653 assert((unsigned)(new_end - new_begin) == size && "Number of indices added not correct?");
10654
10655 return FindScalarValue(I->getAggregateOperand(), new_begin, new_end, InsertBefore);
10656 }
10657 // Otherwise, we don't know (such as, extracting from a function return value
10658 // or load instruction)
10659 return 0;
10660}
10661
10662Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10663 // See if we are trying to extract a known value. If so, use that instead.
10664 if (Value *Elt = FindScalarValue(EV.getOperand(0), EV.idx_begin(), EV.idx_end(), EV))
10665 return ReplaceInstUsesWith(EV, Elt);
10666
10667 // No changes
10668 return 0;
10669}
10670
Chris Lattner220b0cf2006-03-05 00:22:33 +000010671/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10672/// is to leave as a vector operation.
10673static bool CheapToScalarize(Value *V, bool isConstant) {
10674 if (isa<ConstantAggregateZero>(V))
10675 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010676 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010677 if (isConstant) return true;
10678 // If all elts are the same, we can extract.
10679 Constant *Op0 = C->getOperand(0);
10680 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10681 if (C->getOperand(i) != Op0)
10682 return false;
10683 return true;
10684 }
10685 Instruction *I = dyn_cast<Instruction>(V);
10686 if (!I) return false;
10687
10688 // Insert element gets simplified to the inserted element or is deleted if
10689 // this is constant idx extract element and its a constant idx insertelt.
10690 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10691 isa<ConstantInt>(I->getOperand(2)))
10692 return true;
10693 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10694 return true;
10695 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10696 if (BO->hasOneUse() &&
10697 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10698 CheapToScalarize(BO->getOperand(1), isConstant)))
10699 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010700 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10701 if (CI->hasOneUse() &&
10702 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10703 CheapToScalarize(CI->getOperand(1), isConstant)))
10704 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010705
10706 return false;
10707}
10708
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010709/// Read and decode a shufflevector mask.
10710///
10711/// It turns undef elements into values that are larger than the number of
10712/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010713static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10714 unsigned NElts = SVI->getType()->getNumElements();
10715 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10716 return std::vector<unsigned>(NElts, 0);
10717 if (isa<UndefValue>(SVI->getOperand(2)))
10718 return std::vector<unsigned>(NElts, 2*NElts);
10719
10720 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010721 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000010722 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10723 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000010724 Result.push_back(NElts*2); // undef -> 8
10725 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000010726 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010727 return Result;
10728}
10729
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010730/// FindScalarElement - Given a vector and an element number, see if the scalar
10731/// value is already around as a register, for example if it were inserted then
10732/// extracted from the vector.
10733static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010734 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10735 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010736 unsigned Width = PTy->getNumElements();
10737 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010738 return UndefValue::get(PTy->getElementType());
10739
10740 if (isa<UndefValue>(V))
10741 return UndefValue::get(PTy->getElementType());
10742 else if (isa<ConstantAggregateZero>(V))
10743 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010744 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010745 return CP->getOperand(EltNo);
10746 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10747 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010748 if (!isa<ConstantInt>(III->getOperand(2)))
10749 return 0;
10750 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010751
10752 // If this is an insert to the element we are looking for, return the
10753 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010754 if (EltNo == IIElt)
10755 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010756
10757 // Otherwise, the insertelement doesn't modify the value, recurse on its
10758 // vector input.
10759 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010760 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010761 unsigned InEl = getShuffleMask(SVI)[EltNo];
10762 if (InEl < Width)
10763 return FindScalarElement(SVI->getOperand(0), InEl);
10764 else if (InEl < Width*2)
10765 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10766 else
10767 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010768 }
10769
10770 // Otherwise, we don't know.
10771 return 0;
10772}
10773
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010774Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000010775 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010776 if (isa<UndefValue>(EI.getOperand(0)))
10777 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10778
Dan Gohman07a96762007-07-16 14:29:03 +000010779 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010780 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10781 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10782
Reid Spencer9d6565a2007-02-15 02:26:10 +000010783 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000010784 // If vector val is constant with all elements the same, replace EI with
10785 // that element. When the elements are not identical, we cannot replace yet
10786 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000010787 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010788 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010789 if (C->getOperand(i) != op0) {
10790 op0 = 0;
10791 break;
10792 }
10793 if (op0)
10794 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010795 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010796
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010797 // If extracting a specified index from the vector, see if we can recursively
10798 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010799 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010800 unsigned IndexVal = IdxC->getZExtValue();
10801 unsigned VectorWidth =
10802 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10803
10804 // If this is extracting an invalid index, turn this into undef, to avoid
10805 // crashing the code below.
10806 if (IndexVal >= VectorWidth)
10807 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10808
Chris Lattner867b99f2006-10-05 06:55:50 +000010809 // This instruction only demands the single element from the input vector.
10810 // If the input vector has a single use, simplify it based on this use
10811 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010812 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010813 uint64_t UndefElts;
10814 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010815 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010816 UndefElts)) {
10817 EI.setOperand(0, V);
10818 return &EI;
10819 }
10820 }
10821
Reid Spencerb83eb642006-10-20 07:07:24 +000010822 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010823 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010824
10825 // If the this extractelement is directly using a bitcast from a vector of
10826 // the same number of elements, see if we can find the source element from
10827 // it. In this case, we will end up needing to bitcast the scalars.
10828 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10829 if (const VectorType *VT =
10830 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10831 if (VT->getNumElements() == VectorWidth)
10832 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10833 return new BitCastInst(Elt, EI.getType());
10834 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010835 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010836
Chris Lattner73fa49d2006-05-25 22:53:38 +000010837 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010838 if (I->hasOneUse()) {
10839 // Push extractelement into predecessor operation if legal and
10840 // profitable to do so
10841 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010842 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10843 if (CheapToScalarize(BO, isConstantElt)) {
10844 ExtractElementInst *newEI0 =
10845 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10846 EI.getName()+".lhs");
10847 ExtractElementInst *newEI1 =
10848 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10849 EI.getName()+".rhs");
10850 InsertNewInstBefore(newEI0, EI);
10851 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010852 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000010853 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010854 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010855 unsigned AS =
10856 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010857 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10858 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010859 GetElementPtrInst *GEP =
10860 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010861 InsertNewInstBefore(GEP, EI);
10862 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010863 }
10864 }
10865 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10866 // Extracting the inserted element?
10867 if (IE->getOperand(2) == EI.getOperand(1))
10868 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10869 // If the inserted and extracted elements are constants, they must not
10870 // be the same value, extract from the pre-inserted value instead.
10871 if (isa<Constant>(IE->getOperand(2)) &&
10872 isa<Constant>(EI.getOperand(1))) {
10873 AddUsesToWorkList(EI);
10874 EI.setOperand(0, IE->getOperand(0));
10875 return &EI;
10876 }
10877 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10878 // If this is extracting an element from a shufflevector, figure out where
10879 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010880 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10881 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010882 Value *Src;
10883 if (SrcIdx < SVI->getType()->getNumElements())
10884 Src = SVI->getOperand(0);
10885 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10886 SrcIdx -= SVI->getType()->getNumElements();
10887 Src = SVI->getOperand(1);
10888 } else {
10889 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010890 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010891 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010892 }
10893 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010894 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010895 return 0;
10896}
10897
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010898/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10899/// elements from either LHS or RHS, return the shuffle mask and true.
10900/// Otherwise, return false.
10901static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10902 std::vector<Constant*> &Mask) {
10903 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10904 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010905 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010906
10907 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010908 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010909 return true;
10910 } else if (V == LHS) {
10911 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010912 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010913 return true;
10914 } else if (V == RHS) {
10915 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010916 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010917 return true;
10918 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10919 // If this is an insert of an extract from some other vector, include it.
10920 Value *VecOp = IEI->getOperand(0);
10921 Value *ScalarOp = IEI->getOperand(1);
10922 Value *IdxOp = IEI->getOperand(2);
10923
Chris Lattnerd929f062006-04-27 21:14:21 +000010924 if (!isa<ConstantInt>(IdxOp))
10925 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010926 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010927
10928 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10929 // Okay, we can handle this if the vector we are insertinting into is
10930 // transitively ok.
10931 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10932 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010933 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010934 return true;
10935 }
10936 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10937 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010938 EI->getOperand(0)->getType() == V->getType()) {
10939 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010940 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010941
10942 // This must be extracting from either LHS or RHS.
10943 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10944 // Okay, we can handle this if the vector we are insertinting into is
10945 // transitively ok.
10946 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10947 // If so, update the mask to reflect the inserted value.
10948 if (EI->getOperand(0) == LHS) {
10949 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010950 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010951 } else {
10952 assert(EI->getOperand(0) == RHS);
10953 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010954 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010955
10956 }
10957 return true;
10958 }
10959 }
10960 }
10961 }
10962 }
10963 // TODO: Handle shufflevector here!
10964
10965 return false;
10966}
10967
10968/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10969/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10970/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010971static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010972 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010973 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010974 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010975 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010976 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010977
10978 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010979 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010980 return V;
10981 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010982 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010983 return V;
10984 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10985 // If this is an insert of an extract from some other vector, include it.
10986 Value *VecOp = IEI->getOperand(0);
10987 Value *ScalarOp = IEI->getOperand(1);
10988 Value *IdxOp = IEI->getOperand(2);
10989
10990 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10991 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10992 EI->getOperand(0)->getType() == V->getType()) {
10993 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010994 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10995 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010996
10997 // Either the extracted from or inserted into vector must be RHSVec,
10998 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010999 if (EI->getOperand(0) == RHS || RHS == 0) {
11000 RHS = EI->getOperand(0);
11001 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011002 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011003 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011004 return V;
11005 }
11006
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011007 if (VecOp == RHS) {
11008 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011009 // Everything but the extracted element is replaced with the RHS.
11010 for (unsigned i = 0; i != NumElts; ++i) {
11011 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011012 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011013 }
11014 return V;
11015 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011016
11017 // If this insertelement is a chain that comes from exactly these two
11018 // vectors, return the vector and the effective shuffle.
11019 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11020 return EI->getOperand(0);
11021
Chris Lattnerefb47352006-04-15 01:39:45 +000011022 }
11023 }
11024 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011025 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011026
11027 // Otherwise, can't do anything fancy. Return an identity vector.
11028 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011029 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011030 return V;
11031}
11032
11033Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11034 Value *VecOp = IE.getOperand(0);
11035 Value *ScalarOp = IE.getOperand(1);
11036 Value *IdxOp = IE.getOperand(2);
11037
Chris Lattner599ded12007-04-09 01:11:16 +000011038 // Inserting an undef or into an undefined place, remove this.
11039 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11040 ReplaceInstUsesWith(IE, VecOp);
11041
Chris Lattnerefb47352006-04-15 01:39:45 +000011042 // If the inserted element was extracted from some other vector, and if the
11043 // indexes are constant, try to turn this into a shufflevector operation.
11044 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11045 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11046 EI->getOperand(0)->getType() == IE.getType()) {
11047 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011048 unsigned ExtractedIdx =
11049 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011050 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011051
11052 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11053 return ReplaceInstUsesWith(IE, VecOp);
11054
11055 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11056 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11057
11058 // If we are extracting a value from a vector, then inserting it right
11059 // back into the same place, just use the input vector.
11060 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11061 return ReplaceInstUsesWith(IE, VecOp);
11062
11063 // We could theoretically do this for ANY input. However, doing so could
11064 // turn chains of insertelement instructions into a chain of shufflevector
11065 // instructions, and right now we do not merge shufflevectors. As such,
11066 // only do this in a situation where it is clear that there is benefit.
11067 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11068 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11069 // the values of VecOp, except then one read from EIOp0.
11070 // Build a new shuffle mask.
11071 std::vector<Constant*> Mask;
11072 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011073 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011074 else {
11075 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011076 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011077 NumVectorElts));
11078 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011079 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011080 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011081 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011082 }
11083
11084 // If this insertelement isn't used by some other insertelement, turn it
11085 // (and any insertelements it points to), into one big shuffle.
11086 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11087 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011088 Value *RHS = 0;
11089 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11090 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11091 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011092 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011093 }
11094 }
11095 }
11096
11097 return 0;
11098}
11099
11100
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011101Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11102 Value *LHS = SVI.getOperand(0);
11103 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011104 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011105
11106 bool MadeChange = false;
11107
Chris Lattner867b99f2006-10-05 06:55:50 +000011108 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011109 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011110 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11111
Chris Lattnere4929dd2007-01-05 07:36:08 +000011112 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011113 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011114 if (isa<UndefValue>(SVI.getOperand(1))) {
11115 // Scan to see if there are any references to the RHS. If so, replace them
11116 // with undef element refs and set MadeChange to true.
11117 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11118 if (Mask[i] >= e && Mask[i] != 2*e) {
11119 Mask[i] = 2*e;
11120 MadeChange = true;
11121 }
11122 }
11123
11124 if (MadeChange) {
11125 // Remap any references to RHS to use LHS.
11126 std::vector<Constant*> Elts;
11127 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11128 if (Mask[i] == 2*e)
11129 Elts.push_back(UndefValue::get(Type::Int32Ty));
11130 else
11131 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11132 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011133 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011134 }
11135 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011136
Chris Lattner863bcff2006-05-25 23:48:38 +000011137 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11138 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11139 if (LHS == RHS || isa<UndefValue>(LHS)) {
11140 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011141 // shuffle(undef,undef,mask) -> undef.
11142 return ReplaceInstUsesWith(SVI, LHS);
11143 }
11144
Chris Lattner863bcff2006-05-25 23:48:38 +000011145 // Remap any references to RHS to use LHS.
11146 std::vector<Constant*> Elts;
11147 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011148 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011149 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011150 else {
11151 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11152 (Mask[i] < e && isa<UndefValue>(LHS)))
11153 Mask[i] = 2*e; // Turn into undef.
11154 else
11155 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011156 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011157 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011158 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011159 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011160 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011161 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011162 LHS = SVI.getOperand(0);
11163 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011164 MadeChange = true;
11165 }
11166
Chris Lattner7b2e27922006-05-26 00:29:06 +000011167 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011168 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011169
Chris Lattner863bcff2006-05-25 23:48:38 +000011170 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11171 if (Mask[i] >= e*2) continue; // Ignore undef values.
11172 // Is this an identity shuffle of the LHS value?
11173 isLHSID &= (Mask[i] == i);
11174
11175 // Is this an identity shuffle of the RHS value?
11176 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011177 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011178
Chris Lattner863bcff2006-05-25 23:48:38 +000011179 // Eliminate identity shuffles.
11180 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11181 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011182
Chris Lattner7b2e27922006-05-26 00:29:06 +000011183 // If the LHS is a shufflevector itself, see if we can combine it with this
11184 // one without producing an unusual shuffle. Here we are really conservative:
11185 // we are absolutely afraid of producing a shuffle mask not in the input
11186 // program, because the code gen may not be smart enough to turn a merged
11187 // shuffle into two specific shuffles: it may produce worse code. As such,
11188 // we only merge two shuffles if the result is one of the two input shuffle
11189 // masks. In this case, merging the shuffles just removes one instruction,
11190 // which we know is safe. This is good for things like turning:
11191 // (splat(splat)) -> splat.
11192 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11193 if (isa<UndefValue>(RHS)) {
11194 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11195
11196 std::vector<unsigned> NewMask;
11197 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11198 if (Mask[i] >= 2*e)
11199 NewMask.push_back(2*e);
11200 else
11201 NewMask.push_back(LHSMask[Mask[i]]);
11202
11203 // If the result mask is equal to the src shuffle or this shuffle mask, do
11204 // the replacement.
11205 if (NewMask == LHSMask || NewMask == Mask) {
11206 std::vector<Constant*> Elts;
11207 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11208 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011209 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011210 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011211 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011212 }
11213 }
11214 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11215 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011216 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011217 }
11218 }
11219 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011220
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011221 return MadeChange ? &SVI : 0;
11222}
11223
11224
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011225
Chris Lattnerea1c4542004-12-08 23:43:58 +000011226
11227/// TryToSinkInstruction - Try to move the specified instruction from its
11228/// current block into the beginning of DestBlock, which can only happen if it's
11229/// safe to move the instruction past all of the instructions between it and the
11230/// end of its block.
11231static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11232 assert(I->hasOneUse() && "Invariants didn't hold!");
11233
Chris Lattner108e9022005-10-27 17:13:11 +000011234 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011235 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11236 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011237
Chris Lattnerea1c4542004-12-08 23:43:58 +000011238 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011239 if (isa<AllocaInst>(I) && I->getParent() ==
11240 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011241 return false;
11242
Chris Lattner96a52a62004-12-09 07:14:34 +000011243 // We can only sink load instructions if there is nothing between the load and
11244 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011245 if (I->mayReadFromMemory()) {
11246 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011247 Scan != E; ++Scan)
11248 if (Scan->mayWriteToMemory())
11249 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011250 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011251
Dan Gohman02dea8b2008-05-23 21:05:58 +000011252 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011253
Chris Lattner4bc5f802005-08-08 19:11:57 +000011254 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011255 ++NumSunkInst;
11256 return true;
11257}
11258
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011259
11260/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11261/// all reachable code to the worklist.
11262///
11263/// This has a couple of tricks to make the code faster and more powerful. In
11264/// particular, we constant fold and DCE instructions as we go, to avoid adding
11265/// them to the worklist (this significantly speeds up instcombine on code where
11266/// many instructions are dead or constant). Additionally, if we find a branch
11267/// whose condition is a known constant, we only visit the reachable successors.
11268///
11269static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011270 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011271 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011272 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011273 std::vector<BasicBlock*> Worklist;
11274 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011275
Chris Lattner2c7718a2007-03-23 19:17:18 +000011276 while (!Worklist.empty()) {
11277 BB = Worklist.back();
11278 Worklist.pop_back();
11279
11280 // We have now visited this block! If we've already been here, ignore it.
11281 if (!Visited.insert(BB)) continue;
11282
11283 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11284 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011285
Chris Lattner2c7718a2007-03-23 19:17:18 +000011286 // DCE instruction if trivially dead.
11287 if (isInstructionTriviallyDead(Inst)) {
11288 ++NumDeadInst;
11289 DOUT << "IC: DCE: " << *Inst;
11290 Inst->eraseFromParent();
11291 continue;
11292 }
11293
11294 // ConstantProp instruction if trivially constant.
11295 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11296 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11297 Inst->replaceAllUsesWith(C);
11298 ++NumConstProp;
11299 Inst->eraseFromParent();
11300 continue;
11301 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011302
Chris Lattner2c7718a2007-03-23 19:17:18 +000011303 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011304 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011305
11306 // Recursively visit successors. If this is a branch or switch on a
11307 // constant, only visit the reachable successor.
11308 TerminatorInst *TI = BB->getTerminator();
11309 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11310 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11311 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011312 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011313 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011314 continue;
11315 }
11316 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11317 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11318 // See if this is an explicit destination.
11319 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11320 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011321 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011322 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011323 continue;
11324 }
11325
11326 // Otherwise it is the default destination.
11327 Worklist.push_back(SI->getSuccessor(0));
11328 continue;
11329 }
11330 }
11331
11332 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11333 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011334 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011335}
11336
Chris Lattnerec9c3582007-03-03 02:04:50 +000011337bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011338 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011339 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011340
11341 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11342 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011343
Chris Lattnerb3d59702005-07-07 20:40:38 +000011344 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011345 // Do a depth-first traversal of the function, populate the worklist with
11346 // the reachable instructions. Ignore blocks that are not reachable. Keep
11347 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011348 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011349 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011350
Chris Lattnerb3d59702005-07-07 20:40:38 +000011351 // Do a quick scan over the function. If we find any blocks that are
11352 // unreachable, remove any instructions inside of them. This prevents
11353 // the instcombine code from having to deal with some bad special cases.
11354 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11355 if (!Visited.count(BB)) {
11356 Instruction *Term = BB->getTerminator();
11357 while (Term != BB->begin()) { // Remove instrs bottom-up
11358 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011359
Bill Wendlingb7427032006-11-26 09:46:52 +000011360 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011361 ++NumDeadInst;
11362
11363 if (!I->use_empty())
11364 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11365 I->eraseFromParent();
11366 }
11367 }
11368 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011369
Chris Lattnerdbab3862007-03-02 21:28:56 +000011370 while (!Worklist.empty()) {
11371 Instruction *I = RemoveOneFromWorkList();
11372 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011373
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011374 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011375 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011376 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011377 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011378 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011379 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011380
Bill Wendlingb7427032006-11-26 09:46:52 +000011381 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011382
11383 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011384 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011385 continue;
11386 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011387
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011388 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011389 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011390 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011391
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011392 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011393 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011394 ReplaceInstUsesWith(*I, C);
11395
Chris Lattner62b14df2002-09-02 04:59:56 +000011396 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011397 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011398 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011399 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011400 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011401
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000011402 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11403 // See if we can constant fold its operands.
11404 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11405 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11406 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11407 i->set(NewC);
11408 }
11409 }
11410 }
11411
Chris Lattnerea1c4542004-12-08 23:43:58 +000011412 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011413 // FIXME: Remove GetResultInst test when first class support for aggregates
11414 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011415 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011416 BasicBlock *BB = I->getParent();
11417 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11418 if (UserParent != BB) {
11419 bool UserIsSuccessor = false;
11420 // See if the user is one of our successors.
11421 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11422 if (*SI == UserParent) {
11423 UserIsSuccessor = true;
11424 break;
11425 }
11426
11427 // If the user is one of our immediate successors, and if that successor
11428 // only has us as a predecessors (we'd have to split the critical edge
11429 // otherwise), we can keep going.
11430 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11431 next(pred_begin(UserParent)) == pred_end(UserParent))
11432 // Okay, the CFG is simple enough, try to sink this instruction.
11433 Changed |= TryToSinkInstruction(I, UserParent);
11434 }
11435 }
11436
Chris Lattner8a2a3112001-12-14 16:52:21 +000011437 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011438#ifndef NDEBUG
11439 std::string OrigI;
11440#endif
11441 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011442 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011443 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011444 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011445 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011446 DOUT << "IC: Old = " << *I
11447 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011448
Chris Lattnerf523d062004-06-09 05:08:07 +000011449 // Everything uses the new instruction now.
11450 I->replaceAllUsesWith(Result);
11451
11452 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011453 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011454 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011455
Chris Lattner6934a042007-02-11 01:23:03 +000011456 // Move the name to the new instruction first.
11457 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011458
11459 // Insert the new instruction into the basic block...
11460 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011461 BasicBlock::iterator InsertPos = I;
11462
11463 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11464 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11465 ++InsertPos;
11466
11467 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011468
Chris Lattner00d51312004-05-01 23:27:23 +000011469 // Make sure that we reprocess all operands now that we reduced their
11470 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011471 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011472
Chris Lattnerf523d062004-06-09 05:08:07 +000011473 // Instructions can end up on the worklist more than once. Make sure
11474 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011475 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011476
11477 // Erase the old instruction.
11478 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011479 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011480#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011481 DOUT << "IC: Mod = " << OrigI
11482 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011483#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011484
Chris Lattner90ac28c2002-08-02 19:29:35 +000011485 // If the instruction was modified, it's possible that it is now dead.
11486 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011487 if (isInstructionTriviallyDead(I)) {
11488 // Make sure we process all operands now that we are reducing their
11489 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011490 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011491
Chris Lattner00d51312004-05-01 23:27:23 +000011492 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011493 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011494 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011495 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011496 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011497 AddToWorkList(I);
11498 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011499 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011500 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011501 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011502 }
11503 }
11504
Chris Lattnerec9c3582007-03-03 02:04:50 +000011505 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011506
11507 // Do an explicit clear, this shrinks the map if needed.
11508 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011509 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011510}
11511
Chris Lattnerec9c3582007-03-03 02:04:50 +000011512
11513bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011514 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11515
Chris Lattnerec9c3582007-03-03 02:04:50 +000011516 bool EverMadeChange = false;
11517
11518 // Iterate while there is work to do.
11519 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011520 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011521 EverMadeChange = true;
11522 return EverMadeChange;
11523}
11524
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011525FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011526 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011527}
Brian Gaeked0fde302003-11-11 22:41:34 +000011528