blob: 802102c99a2d4c4e5a64e317fdf2dfdce9bcbf64 [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
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000402 };
403}
404
Dan Gohman844731a2008-05-13 00:00:25 +0000405char InstCombiner::ID = 0;
406static RegisterPass<InstCombiner>
407X("instcombine", "Combine redundant instructions");
408
Chris Lattner4f98c562003-03-10 21:43:22 +0000409// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000410// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000411static unsigned getComplexity(Value *V) {
412 if (isa<Instruction>(V)) {
413 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000414 return 3;
415 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000416 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000417 if (isa<Argument>(V)) return 3;
418 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000419}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000420
Chris Lattnerc8802d22003-03-11 00:12:48 +0000421// isOnlyUse - Return true if this instruction will be deleted if we stop using
422// it.
423static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000424 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000425}
426
Chris Lattner4cb170c2004-02-23 06:38:22 +0000427// getPromotedType - Return the specified type promoted as it would be to pass
428// though a va_arg area...
429static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000430 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431 if (ITy->getBitWidth() < 32)
432 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000433 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000434 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000435}
436
Reid Spencer3da59db2006-11-27 01:05:10 +0000437/// getBitCastOperand - If the specified operand is a CastInst or a constant
438/// expression bitcast, return the operand value, otherwise return null.
439static Value *getBitCastOperand(Value *V) {
440 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000441 return I->getOperand(0);
442 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000443 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000444 return CE->getOperand(0);
445 return 0;
446}
447
Reid Spencer3da59db2006-11-27 01:05:10 +0000448/// This function is a wrapper around CastInst::isEliminableCastPair. It
449/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000450static Instruction::CastOps
451isEliminableCastPair(
452 const CastInst *CI, ///< The first cast instruction
453 unsigned opcode, ///< The opcode of the second cast instruction
454 const Type *DstTy, ///< The target type for the second cast instruction
455 TargetData *TD ///< The target data for pointer size
456) {
457
458 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
459 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000460
Reid Spencer3da59db2006-11-27 01:05:10 +0000461 // Get the opcodes of the two Cast instructions
462 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
463 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000464
Reid Spencer3da59db2006-11-27 01:05:10 +0000465 return Instruction::CastOps(
466 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
467 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000468}
469
470/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
471/// in any code being generated. It does not require codegen if V is simple
472/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000473static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
474 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000475 if (V->getType() == Ty || isa<Constant>(V)) return false;
476
Chris Lattner01575b72006-05-25 23:24:33 +0000477 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000478 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000479 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000480 return false;
481 return true;
482}
483
484/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
485/// InsertBefore instruction. This is specialized a bit to avoid inserting
486/// casts that are known to not do anything...
487///
Reid Spencer17212df2006-12-12 09:18:51 +0000488Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
489 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000490 Instruction *InsertBefore) {
491 if (V->getType() == DestTy) return V;
492 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000493 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000494
Reid Spencer17212df2006-12-12 09:18:51 +0000495 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000496}
497
Chris Lattner4f98c562003-03-10 21:43:22 +0000498// SimplifyCommutative - This performs a few simplifications for commutative
499// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000500//
Chris Lattner4f98c562003-03-10 21:43:22 +0000501// 1. Order operands such that they are listed from right (least complex) to
502// left (most complex). This puts constants before unary operators before
503// binary operators.
504//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000505// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
506// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000507//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000508bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000509 bool Changed = false;
510 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
511 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000512
Chris Lattner4f98c562003-03-10 21:43:22 +0000513 if (!I.isAssociative()) return Changed;
514 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000515 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
516 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
517 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000518 Constant *Folded = ConstantExpr::get(I.getOpcode(),
519 cast<Constant>(I.getOperand(1)),
520 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521 I.setOperand(0, Op->getOperand(0));
522 I.setOperand(1, Folded);
523 return true;
524 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
525 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
526 isOnlyUse(Op) && isOnlyUse(Op1)) {
527 Constant *C1 = cast<Constant>(Op->getOperand(1));
528 Constant *C2 = cast<Constant>(Op1->getOperand(1));
529
530 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000531 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000532 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000533 Op1->getOperand(0),
534 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000535 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000536 I.setOperand(0, New);
537 I.setOperand(1, Folded);
538 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000539 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000540 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000541 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000542}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000543
Reid Spencere4d87aa2006-12-23 06:05:41 +0000544/// SimplifyCompare - For a CmpInst this function just orders the operands
545/// so that theyare listed from right (least complex) to left (most complex).
546/// This puts constants before unary operators before binary operators.
547bool InstCombiner::SimplifyCompare(CmpInst &I) {
548 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
549 return false;
550 I.swapOperands();
551 // Compare instructions are not associative so there's nothing else we can do.
552 return true;
553}
554
Chris Lattner8d969642003-03-10 23:06:50 +0000555// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
556// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000557//
Chris Lattner8d969642003-03-10 23:06:50 +0000558static inline Value *dyn_castNegVal(Value *V) {
559 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000560 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000561
Chris Lattner0ce85802004-12-14 20:08:06 +0000562 // Constants can be considered to be negated values if they can be folded.
563 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
564 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000565
566 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
567 if (C->getType()->getElementType()->isInteger())
568 return ConstantExpr::getNeg(C);
569
Chris Lattner8d969642003-03-10 23:06:50 +0000570 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000571}
572
Chris Lattner8d969642003-03-10 23:06:50 +0000573static inline Value *dyn_castNotVal(Value *V) {
574 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000575 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000576
577 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000578 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000579 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000580 return 0;
581}
582
Chris Lattnerc8802d22003-03-11 00:12:48 +0000583// dyn_castFoldableMul - If this value is a multiply that can be folded into
584// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000585// non-constant operand of the multiply, and set CST to point to the multiplier.
586// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000587//
Chris Lattner50af16a2004-11-13 19:50:12 +0000588static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000589 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000590 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000592 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000593 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000594 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000595 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000596 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000597 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000598 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000599 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000600 return I->getOperand(0);
601 }
602 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000603 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000604}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000605
Chris Lattner574da9b2005-01-13 20:14:25 +0000606/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
607/// expression, return it.
608static User *dyn_castGetElementPtr(Value *V) {
609 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
610 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
611 if (CE->getOpcode() == Instruction::GetElementPtr)
612 return cast<User>(V);
613 return false;
614}
615
Dan Gohmaneee962e2008-04-10 18:43:06 +0000616/// getOpcode - If this is an Instruction or a ConstantExpr, return the
617/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000618static unsigned getOpcode(const Value *V) {
619 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000620 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000621 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000622 return CE->getOpcode();
623 // Use UserOp1 to mean there's no opcode.
624 return Instruction::UserOp1;
625}
626
Reid Spencer7177c3a2007-03-25 05:33:51 +0000627/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000628static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000629 APInt Val(C->getValue());
630 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000631}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000632/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000633static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000634 APInt Val(C->getValue());
635 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000636}
637/// Add - Add two ConstantInts together
638static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() + C2->getValue());
640}
641/// And - Bitwise AND two ConstantInts together
642static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
643 return ConstantInt::get(C1->getValue() & C2->getValue());
644}
645/// Subtract - Subtract one ConstantInt from another
646static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
647 return ConstantInt::get(C1->getValue() - C2->getValue());
648}
649/// Multiply - Multiply two ConstantInts together
650static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
651 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000652}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000653/// MultiplyOverflows - True if the multiply can not be expressed in an int
654/// this size.
655static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
656 uint32_t W = C1->getBitWidth();
657 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
658 if (sign) {
659 LHSExt.sext(W * 2);
660 RHSExt.sext(W * 2);
661 } else {
662 LHSExt.zext(W * 2);
663 RHSExt.zext(W * 2);
664 }
665
666 APInt MulExt = LHSExt * RHSExt;
667
668 if (sign) {
669 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
670 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
671 return MulExt.slt(Min) || MulExt.sgt(Max);
672 } else
673 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
674}
Chris Lattner955f3312004-09-28 21:48:02 +0000675
Reid Spencere7816b52007-03-08 01:52:58 +0000676
Chris Lattner255d8912006-02-11 09:31:47 +0000677/// ShrinkDemandedConstant - Check to see if the specified operand of the
678/// specified instruction is a constant integer. If so, check to see if there
679/// are any bits set in the constant that are not demanded. If so, shrink the
680/// constant and return true.
681static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000682 APInt Demanded) {
683 assert(I && "No instruction?");
684 assert(OpNo < I->getNumOperands() && "Operand index too large");
685
686 // If the operand is not a constant integer, nothing to do.
687 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
688 if (!OpC) return false;
689
690 // If there are no bits set that aren't demanded, nothing to do.
691 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
692 if ((~Demanded & OpC->getValue()) == 0)
693 return false;
694
695 // This instruction is producing bits that are not demanded. Shrink the RHS.
696 Demanded &= OpC->getValue();
697 I->setOperand(OpNo, ConstantInt::get(Demanded));
698 return true;
699}
700
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000701// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
702// set of known zero and one bits, compute the maximum and minimum values that
703// could have the specified known zero and known one bits, returning them in
704// min/max.
705static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000706 const APInt& KnownZero,
707 const APInt& KnownOne,
708 APInt& Min, APInt& Max) {
709 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
710 assert(KnownZero.getBitWidth() == BitWidth &&
711 KnownOne.getBitWidth() == BitWidth &&
712 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
713 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000714 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000715
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000716 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
717 // bit if it is unknown.
718 Min = KnownOne;
719 Max = KnownOne|UnknownBits;
720
Zhou Sheng4acf1552007-03-28 05:15:57 +0000721 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000722 Min.set(BitWidth-1);
723 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000724 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000725}
726
727// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
728// a set of known zero and one bits, compute the maximum and minimum values that
729// could have the specified known zero and known one bits, returning them in
730// min/max.
731static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000732 const APInt &KnownZero,
733 const APInt &KnownOne,
734 APInt &Min, APInt &Max) {
735 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000736 assert(KnownZero.getBitWidth() == BitWidth &&
737 KnownOne.getBitWidth() == BitWidth &&
738 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
739 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000740 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000741
742 // The minimum value is when the unknown bits are all zeros.
743 Min = KnownOne;
744 // The maximum value is when the unknown bits are all ones.
745 Max = KnownOne|UnknownBits;
746}
Chris Lattner255d8912006-02-11 09:31:47 +0000747
Reid Spencer8cb68342007-03-12 17:25:59 +0000748/// SimplifyDemandedBits - This function attempts to replace V with a simpler
749/// value based on the demanded bits. When this function is called, it is known
750/// that only the bits set in DemandedMask of the result of V are ever used
751/// downstream. Consequently, depending on the mask and V, it may be possible
752/// to replace V with a constant or one of its operands. In such cases, this
753/// function does the replacement and returns true. In all other cases, it
754/// returns false after analyzing the expression and setting KnownOne and known
755/// to be one in the expression. KnownZero contains all the bits that are known
756/// to be zero in the expression. These are provided to potentially allow the
757/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
758/// the expression. KnownOne and KnownZero always follow the invariant that
759/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
760/// the bits in KnownOne and KnownZero may only be accurate for those bits set
761/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
762/// and KnownOne must all be the same.
763bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
764 APInt& KnownZero, APInt& KnownOne,
765 unsigned Depth) {
766 assert(V != 0 && "Null pointer of Value???");
767 assert(Depth <= 6 && "Limit Search Depth");
768 uint32_t BitWidth = DemandedMask.getBitWidth();
769 const IntegerType *VTy = cast<IntegerType>(V->getType());
770 assert(VTy->getBitWidth() == BitWidth &&
771 KnownZero.getBitWidth() == BitWidth &&
772 KnownOne.getBitWidth() == BitWidth &&
773 "Value *V, DemandedMask, KnownZero and KnownOne \
774 must have same BitWidth");
775 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
776 // We know all of the bits for a constant!
777 KnownOne = CI->getValue() & DemandedMask;
778 KnownZero = ~KnownOne & DemandedMask;
779 return false;
780 }
781
Zhou Sheng96704452007-03-14 03:21:24 +0000782 KnownZero.clear();
783 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000784 if (!V->hasOneUse()) { // Other users may use these bits.
785 if (Depth != 0) { // Not at the root.
786 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
787 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
788 return false;
789 }
790 // If this is the root being simplified, allow it to have multiple uses,
791 // just set the DemandedMask to all bits.
792 DemandedMask = APInt::getAllOnesValue(BitWidth);
793 } else if (DemandedMask == 0) { // Not demanding any bits from V.
794 if (V != UndefValue::get(VTy))
795 return UpdateValueUsesWith(V, UndefValue::get(VTy));
796 return false;
797 } else if (Depth == 6) { // Limit search depth.
798 return false;
799 }
800
801 Instruction *I = dyn_cast<Instruction>(V);
802 if (!I) return false; // Only analyze instructions.
803
Reid Spencer8cb68342007-03-12 17:25:59 +0000804 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
805 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
806 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000807 default:
808 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
809 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000810 case Instruction::And:
811 // If either the LHS or the RHS are Zero, the result is zero.
812 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
813 RHSKnownZero, RHSKnownOne, Depth+1))
814 return true;
815 assert((RHSKnownZero & RHSKnownOne) == 0 &&
816 "Bits known to be one AND zero?");
817
818 // If something is known zero on the RHS, the bits aren't demanded on the
819 // LHS.
820 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
821 LHSKnownZero, LHSKnownOne, Depth+1))
822 return true;
823 assert((LHSKnownZero & LHSKnownOne) == 0 &&
824 "Bits known to be one AND zero?");
825
826 // If all of the demanded bits are known 1 on one side, return the other.
827 // These bits cannot contribute to the result of the 'and'.
828 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
829 (DemandedMask & ~LHSKnownZero))
830 return UpdateValueUsesWith(I, I->getOperand(0));
831 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
832 (DemandedMask & ~RHSKnownZero))
833 return UpdateValueUsesWith(I, I->getOperand(1));
834
835 // If all of the demanded bits in the inputs are known zeros, return zero.
836 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
837 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
838
839 // If the RHS is a constant, see if we can simplify it.
840 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
841 return UpdateValueUsesWith(I, I);
842
843 // Output known-1 bits are only known if set in both the LHS & RHS.
844 RHSKnownOne &= LHSKnownOne;
845 // Output known-0 are known to be clear if zero in either the LHS | RHS.
846 RHSKnownZero |= LHSKnownZero;
847 break;
848 case Instruction::Or:
849 // If either the LHS or the RHS are One, the result is One.
850 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
851 RHSKnownZero, RHSKnownOne, Depth+1))
852 return true;
853 assert((RHSKnownZero & RHSKnownOne) == 0 &&
854 "Bits known to be one AND zero?");
855 // If something is known one on the RHS, the bits aren't demanded on the
856 // LHS.
857 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
858 LHSKnownZero, LHSKnownOne, Depth+1))
859 return true;
860 assert((LHSKnownZero & LHSKnownOne) == 0 &&
861 "Bits known to be one AND zero?");
862
863 // If all of the demanded bits are known zero on one side, return the other.
864 // These bits cannot contribute to the result of the 'or'.
865 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
866 (DemandedMask & ~LHSKnownOne))
867 return UpdateValueUsesWith(I, I->getOperand(0));
868 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
869 (DemandedMask & ~RHSKnownOne))
870 return UpdateValueUsesWith(I, I->getOperand(1));
871
872 // If all of the potentially set bits on one side are known to be set on
873 // the other side, just use the 'other' side.
874 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
875 (DemandedMask & (~RHSKnownZero)))
876 return UpdateValueUsesWith(I, I->getOperand(0));
877 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
878 (DemandedMask & (~LHSKnownZero)))
879 return UpdateValueUsesWith(I, I->getOperand(1));
880
881 // If the RHS is a constant, see if we can simplify it.
882 if (ShrinkDemandedConstant(I, 1, DemandedMask))
883 return UpdateValueUsesWith(I, I);
884
885 // Output known-0 bits are only known if clear in both the LHS & RHS.
886 RHSKnownZero &= LHSKnownZero;
887 // Output known-1 are known to be set if set in either the LHS | RHS.
888 RHSKnownOne |= LHSKnownOne;
889 break;
890 case Instruction::Xor: {
891 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
892 RHSKnownZero, RHSKnownOne, Depth+1))
893 return true;
894 assert((RHSKnownZero & RHSKnownOne) == 0 &&
895 "Bits known to be one AND zero?");
896 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
897 LHSKnownZero, LHSKnownOne, Depth+1))
898 return true;
899 assert((LHSKnownZero & LHSKnownOne) == 0 &&
900 "Bits known to be one AND zero?");
901
902 // If all of the demanded bits are known zero on one side, return the other.
903 // These bits cannot contribute to the result of the 'xor'.
904 if ((DemandedMask & RHSKnownZero) == DemandedMask)
905 return UpdateValueUsesWith(I, I->getOperand(0));
906 if ((DemandedMask & LHSKnownZero) == DemandedMask)
907 return UpdateValueUsesWith(I, I->getOperand(1));
908
909 // Output known-0 bits are known if clear or set in both the LHS & RHS.
910 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
911 (RHSKnownOne & LHSKnownOne);
912 // Output known-1 are known to be set if set in only one of the LHS, RHS.
913 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
914 (RHSKnownOne & LHSKnownZero);
915
916 // If all of the demanded bits are known to be zero on one side or the
917 // other, turn this into an *inclusive* or.
918 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
919 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
920 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000921 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +0000922 I->getName());
923 InsertNewInstBefore(Or, *I);
924 return UpdateValueUsesWith(I, Or);
925 }
926
927 // If all of the demanded bits on one side are known, and all of the set
928 // bits on that side are also known to be set on the other side, turn this
929 // into an AND, as we know the bits will be cleared.
930 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
931 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
932 // all known
933 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
934 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
935 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000936 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +0000937 InsertNewInstBefore(And, *I);
938 return UpdateValueUsesWith(I, And);
939 }
940 }
941
942 // If the RHS is a constant, see if we can simplify it.
943 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
944 if (ShrinkDemandedConstant(I, 1, DemandedMask))
945 return UpdateValueUsesWith(I, I);
946
947 RHSKnownZero = KnownZeroOut;
948 RHSKnownOne = KnownOneOut;
949 break;
950 }
951 case Instruction::Select:
952 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
953 RHSKnownZero, RHSKnownOne, Depth+1))
954 return true;
955 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
956 LHSKnownZero, LHSKnownOne, Depth+1))
957 return true;
958 assert((RHSKnownZero & RHSKnownOne) == 0 &&
959 "Bits known to be one AND zero?");
960 assert((LHSKnownZero & LHSKnownOne) == 0 &&
961 "Bits known to be one AND zero?");
962
963 // If the operands are constants, see if we can simplify them.
964 if (ShrinkDemandedConstant(I, 1, DemandedMask))
965 return UpdateValueUsesWith(I, I);
966 if (ShrinkDemandedConstant(I, 2, DemandedMask))
967 return UpdateValueUsesWith(I, I);
968
969 // Only known if known in both the LHS and RHS.
970 RHSKnownOne &= LHSKnownOne;
971 RHSKnownZero &= LHSKnownZero;
972 break;
973 case Instruction::Trunc: {
974 uint32_t truncBf =
975 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +0000976 DemandedMask.zext(truncBf);
977 RHSKnownZero.zext(truncBf);
978 RHSKnownOne.zext(truncBf);
979 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
980 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +0000981 return true;
982 DemandedMask.trunc(BitWidth);
983 RHSKnownZero.trunc(BitWidth);
984 RHSKnownOne.trunc(BitWidth);
985 assert((RHSKnownZero & RHSKnownOne) == 0 &&
986 "Bits known to be one AND zero?");
987 break;
988 }
989 case Instruction::BitCast:
990 if (!I->getOperand(0)->getType()->isInteger())
991 return false;
992
993 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
994 RHSKnownZero, RHSKnownOne, Depth+1))
995 return true;
996 assert((RHSKnownZero & RHSKnownOne) == 0 &&
997 "Bits known to be one AND zero?");
998 break;
999 case Instruction::ZExt: {
1000 // Compute the bits in the result that are not present in the input.
1001 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001002 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001003
Zhou Shengd48653a2007-03-29 04:45:55 +00001004 DemandedMask.trunc(SrcBitWidth);
1005 RHSKnownZero.trunc(SrcBitWidth);
1006 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001007 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001009 return true;
1010 DemandedMask.zext(BitWidth);
1011 RHSKnownZero.zext(BitWidth);
1012 RHSKnownOne.zext(BitWidth);
1013 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1014 "Bits known to be one AND zero?");
1015 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001016 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001017 break;
1018 }
1019 case Instruction::SExt: {
1020 // Compute the bits in the result that are not present in the input.
1021 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001022 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001023
Reid Spencer8cb68342007-03-12 17:25:59 +00001024 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001025 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001026
Zhou Sheng01542f32007-03-29 02:26:30 +00001027 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001028 // If any of the sign extended bits are demanded, we know that the sign
1029 // bit is demanded.
1030 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001031 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001032
Zhou Shengd48653a2007-03-29 04:45:55 +00001033 InputDemandedBits.trunc(SrcBitWidth);
1034 RHSKnownZero.trunc(SrcBitWidth);
1035 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001036 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1037 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001038 return true;
1039 InputDemandedBits.zext(BitWidth);
1040 RHSKnownZero.zext(BitWidth);
1041 RHSKnownOne.zext(BitWidth);
1042 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1043 "Bits known to be one AND zero?");
1044
1045 // If the sign bit of the input is known set or clear, then we know the
1046 // top bits of the result.
1047
1048 // If the input sign bit is known zero, or if the NewBits are not demanded
1049 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001050 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001051 {
1052 // Convert to ZExt cast
1053 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1054 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001055 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001056 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001057 }
1058 break;
1059 }
1060 case Instruction::Add: {
1061 // Figure out what the input bits are. If the top bits of the and result
1062 // are not demanded, then the add doesn't demand them from its input
1063 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001064 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001065
1066 // If there is a constant on the RHS, there are a variety of xformations
1067 // we can do.
1068 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1069 // If null, this should be simplified elsewhere. Some of the xforms here
1070 // won't work if the RHS is zero.
1071 if (RHS->isZero())
1072 break;
1073
1074 // If the top bit of the output is demanded, demand everything from the
1075 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001076 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001077
1078 // Find information about known zero/one bits in the input.
1079 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1080 LHSKnownZero, LHSKnownOne, Depth+1))
1081 return true;
1082
1083 // If the RHS of the add has bits set that can't affect the input, reduce
1084 // the constant.
1085 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1086 return UpdateValueUsesWith(I, I);
1087
1088 // Avoid excess work.
1089 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1090 break;
1091
1092 // Turn it into OR if input bits are zero.
1093 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1094 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001095 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001096 I->getName());
1097 InsertNewInstBefore(Or, *I);
1098 return UpdateValueUsesWith(I, Or);
1099 }
1100
1101 // We can say something about the output known-zero and known-one bits,
1102 // depending on potential carries from the input constant and the
1103 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1104 // bits set and the RHS constant is 0x01001, then we know we have a known
1105 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1106
1107 // To compute this, we first compute the potential carry bits. These are
1108 // the bits which may be modified. I'm not aware of a better way to do
1109 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001110 const APInt& RHSVal = RHS->getValue();
1111 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001112
1113 // Now that we know which bits have carries, compute the known-1/0 sets.
1114
1115 // Bits are known one if they are known zero in one operand and one in the
1116 // other, and there is no input carry.
1117 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1118 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1119
1120 // Bits are known zero if they are known zero in both operands and there
1121 // is no input carry.
1122 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1123 } else {
1124 // If the high-bits of this ADD are not demanded, then it does not demand
1125 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001126 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001127 // Right fill the mask of bits for this ADD to demand the most
1128 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001129 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001130 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1131 LHSKnownZero, LHSKnownOne, Depth+1))
1132 return true;
1133 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1134 LHSKnownZero, LHSKnownOne, Depth+1))
1135 return true;
1136 }
1137 }
1138 break;
1139 }
1140 case Instruction::Sub:
1141 // If the high-bits of this SUB are not demanded, then it does not demand
1142 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001143 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001144 // Right fill the mask of bits for this SUB to demand the most
1145 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001146 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001147 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001148 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1149 LHSKnownZero, LHSKnownOne, Depth+1))
1150 return true;
1151 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1152 LHSKnownZero, LHSKnownOne, Depth+1))
1153 return true;
1154 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001155 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1156 // the known zeros and ones.
1157 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001158 break;
1159 case Instruction::Shl:
1160 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001161 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001162 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1163 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001164 RHSKnownZero, RHSKnownOne, Depth+1))
1165 return true;
1166 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1167 "Bits known to be one AND zero?");
1168 RHSKnownZero <<= ShiftAmt;
1169 RHSKnownOne <<= ShiftAmt;
1170 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001171 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001172 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001173 }
1174 break;
1175 case Instruction::LShr:
1176 // For a logical shift right
1177 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001178 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001179
Reid Spencer8cb68342007-03-12 17:25:59 +00001180 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001181 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1182 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001183 RHSKnownZero, RHSKnownOne, Depth+1))
1184 return true;
1185 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1186 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1188 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001189 if (ShiftAmt) {
1190 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001191 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001192 RHSKnownZero |= HighBits; // high bits known zero.
1193 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001194 }
1195 break;
1196 case Instruction::AShr:
1197 // If this is an arithmetic shift right and only the low-bit is set, we can
1198 // always convert this into a logical shr, even if the shift amount is
1199 // variable. The low bit of the shift cannot be an input sign bit unless
1200 // the shift amount is >= the size of the datatype, which is undefined.
1201 if (DemandedMask == 1) {
1202 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001203 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001204 I->getOperand(0), I->getOperand(1), I->getName());
1205 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1206 return UpdateValueUsesWith(I, NewVal);
1207 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001208
1209 // If the sign bit is the only bit demanded by this ashr, then there is no
1210 // need to do it, the shift doesn't change the high bit.
1211 if (DemandedMask.isSignBit())
1212 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001213
1214 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001215 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001216
Reid Spencer8cb68342007-03-12 17:25:59 +00001217 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001218 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001219 // If any of the "high bits" are demanded, we should set the sign bit as
1220 // demanded.
1221 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1222 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001223 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001224 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 RHSKnownZero, RHSKnownOne, Depth+1))
1226 return true;
1227 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1228 "Bits known to be one AND zero?");
1229 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001230 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1232 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1233
1234 // Handle the sign bits.
1235 APInt SignBit(APInt::getSignBit(BitWidth));
1236 // Adjust to where it is now in the mask.
1237 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1238
1239 // If the input sign bit is known to be zero, or if none of the top bits
1240 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001241 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001242 (HighBits & ~DemandedMask) == HighBits) {
1243 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001244 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 I->getOperand(0), SA, I->getName());
1246 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1247 return UpdateValueUsesWith(I, NewVal);
1248 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1249 RHSKnownOne |= HighBits;
1250 }
1251 }
1252 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001253 case Instruction::SRem:
1254 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1255 APInt RA = Rem->getValue();
1256 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001257 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001258 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1259 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1260 LHSKnownZero, LHSKnownOne, Depth+1))
1261 return true;
1262
1263 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1264 LHSKnownZero |= ~LowBits;
1265 else if (LHSKnownOne[BitWidth-1])
1266 LHSKnownOne |= ~LowBits;
1267
1268 KnownZero |= LHSKnownZero & DemandedMask;
1269 KnownOne |= LHSKnownOne & DemandedMask;
1270
1271 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1272 }
1273 }
1274 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001275 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001276 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1277 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001278 if (RA.isPowerOf2()) {
1279 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001280 APInt Mask2 = LowBits & DemandedMask;
1281 KnownZero |= ~LowBits & DemandedMask;
1282 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1283 KnownZero, KnownOne, Depth+1))
1284 return true;
1285
1286 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001287 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001288 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001289 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001290
1291 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1292 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001293 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1294 KnownZero2, KnownOne2, Depth+1))
1295 return true;
1296
Dan Gohman23e8b712008-04-28 17:02:21 +00001297 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001298 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001299 KnownZero2, KnownOne2, Depth+1))
1300 return true;
1301
1302 Leaders = std::max(Leaders,
1303 KnownZero2.countLeadingOnes());
1304 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001305 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001306 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001307 case Instruction::Call:
1308 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1309 switch (II->getIntrinsicID()) {
1310 default: break;
1311 case Intrinsic::bswap: {
1312 // If the only bits demanded come from one byte of the bswap result,
1313 // just shift the input byte into position to eliminate the bswap.
1314 unsigned NLZ = DemandedMask.countLeadingZeros();
1315 unsigned NTZ = DemandedMask.countTrailingZeros();
1316
1317 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1318 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1319 // have 14 leading zeros, round to 8.
1320 NLZ &= ~7;
1321 NTZ &= ~7;
1322 // If we need exactly one byte, we can do this transformation.
1323 if (BitWidth-NLZ-NTZ == 8) {
1324 unsigned ResultBit = NTZ;
1325 unsigned InputBit = BitWidth-NTZ-8;
1326
1327 // Replace this with either a left or right shift to get the byte into
1328 // the right place.
1329 Instruction *NewVal;
1330 if (InputBit > ResultBit)
1331 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1332 ConstantInt::get(I->getType(), InputBit-ResultBit));
1333 else
1334 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1335 ConstantInt::get(I->getType(), ResultBit-InputBit));
1336 NewVal->takeName(I);
1337 InsertNewInstBefore(NewVal, *I);
1338 return UpdateValueUsesWith(I, NewVal);
1339 }
1340
1341 // TODO: Could compute known zero/one bits based on the input.
1342 break;
1343 }
1344 }
1345 }
1346 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001347 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001348
1349 // If the client is only demanding bits that we know, return the known
1350 // constant.
1351 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1352 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1353 return false;
1354}
1355
Chris Lattner867b99f2006-10-05 06:55:50 +00001356
1357/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1358/// 64 or fewer elements. DemandedElts contains the set of elements that are
1359/// actually used by the caller. This method analyzes which elements of the
1360/// operand are undef and returns that information in UndefElts.
1361///
1362/// If the information about demanded elements can be used to simplify the
1363/// operation, the operation is simplified, then the resultant value is
1364/// returned. This returns null if no change was made.
1365Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1366 uint64_t &UndefElts,
1367 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001368 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001369 assert(VWidth <= 64 && "Vector too wide to analyze!");
1370 uint64_t EltMask = ~0ULL >> (64-VWidth);
1371 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1372 "Invalid DemandedElts!");
1373
1374 if (isa<UndefValue>(V)) {
1375 // If the entire vector is undefined, just return this info.
1376 UndefElts = EltMask;
1377 return 0;
1378 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1379 UndefElts = EltMask;
1380 return UndefValue::get(V->getType());
1381 }
1382
1383 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001384 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1385 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001386 Constant *Undef = UndefValue::get(EltTy);
1387
1388 std::vector<Constant*> Elts;
1389 for (unsigned i = 0; i != VWidth; ++i)
1390 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1391 Elts.push_back(Undef);
1392 UndefElts |= (1ULL << i);
1393 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1394 Elts.push_back(Undef);
1395 UndefElts |= (1ULL << i);
1396 } else { // Otherwise, defined.
1397 Elts.push_back(CP->getOperand(i));
1398 }
1399
1400 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001401 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001402 return NewCP != CP ? NewCP : 0;
1403 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001404 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001405 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001406 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001407 Constant *Zero = Constant::getNullValue(EltTy);
1408 Constant *Undef = UndefValue::get(EltTy);
1409 std::vector<Constant*> Elts;
1410 for (unsigned i = 0; i != VWidth; ++i)
1411 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1412 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001413 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001414 }
1415
1416 if (!V->hasOneUse()) { // Other users may use these bits.
1417 if (Depth != 0) { // Not at the root.
1418 // TODO: Just compute the UndefElts information recursively.
1419 return false;
1420 }
1421 return false;
1422 } else if (Depth == 10) { // Limit search depth.
1423 return false;
1424 }
1425
1426 Instruction *I = dyn_cast<Instruction>(V);
1427 if (!I) return false; // Only analyze instructions.
1428
1429 bool MadeChange = false;
1430 uint64_t UndefElts2;
1431 Value *TmpV;
1432 switch (I->getOpcode()) {
1433 default: break;
1434
1435 case Instruction::InsertElement: {
1436 // If this is a variable index, we don't know which element it overwrites.
1437 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001438 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001439 if (Idx == 0) {
1440 // Note that we can't propagate undef elt info, because we don't know
1441 // which elt is getting updated.
1442 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1443 UndefElts2, Depth+1);
1444 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1445 break;
1446 }
1447
1448 // If this is inserting an element that isn't demanded, remove this
1449 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001450 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001451 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1452 return AddSoonDeadInstToWorklist(*I, 0);
1453
1454 // Otherwise, the element inserted overwrites whatever was there, so the
1455 // input demanded set is simpler than the output set.
1456 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1457 DemandedElts & ~(1ULL << IdxNo),
1458 UndefElts, Depth+1);
1459 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1460
1461 // The inserted element is defined.
1462 UndefElts |= 1ULL << IdxNo;
1463 break;
1464 }
Chris Lattner69878332007-04-14 22:29:23 +00001465 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001466 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001467 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1468 if (!VTy) break;
1469 unsigned InVWidth = VTy->getNumElements();
1470 uint64_t InputDemandedElts = 0;
1471 unsigned Ratio;
1472
1473 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001474 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001475 // elements as are demanded of us.
1476 Ratio = 1;
1477 InputDemandedElts = DemandedElts;
1478 } else if (VWidth > InVWidth) {
1479 // Untested so far.
1480 break;
1481
1482 // If there are more elements in the result than there are in the source,
1483 // then an input element is live if any of the corresponding output
1484 // elements are live.
1485 Ratio = VWidth/InVWidth;
1486 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1487 if (DemandedElts & (1ULL << OutIdx))
1488 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1489 }
1490 } else {
1491 // Untested so far.
1492 break;
1493
1494 // If there are more elements in the source than there are in the result,
1495 // then an input element is live if the corresponding output element is
1496 // live.
1497 Ratio = InVWidth/VWidth;
1498 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1499 if (DemandedElts & (1ULL << InIdx/Ratio))
1500 InputDemandedElts |= 1ULL << InIdx;
1501 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001502
Chris Lattner69878332007-04-14 22:29:23 +00001503 // div/rem demand all inputs, because they don't want divide by zero.
1504 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1505 UndefElts2, Depth+1);
1506 if (TmpV) {
1507 I->setOperand(0, TmpV);
1508 MadeChange = true;
1509 }
1510
1511 UndefElts = UndefElts2;
1512 if (VWidth > InVWidth) {
1513 assert(0 && "Unimp");
1514 // If there are more elements in the result than there are in the source,
1515 // then an output element is undef if the corresponding input element is
1516 // undef.
1517 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1518 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1519 UndefElts |= 1ULL << OutIdx;
1520 } else if (VWidth < InVWidth) {
1521 assert(0 && "Unimp");
1522 // If there are more elements in the source than there are in the result,
1523 // then a result element is undef if all of the corresponding input
1524 // elements are undef.
1525 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1526 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1527 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1528 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1529 }
1530 break;
1531 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001532 case Instruction::And:
1533 case Instruction::Or:
1534 case Instruction::Xor:
1535 case Instruction::Add:
1536 case Instruction::Sub:
1537 case Instruction::Mul:
1538 // div/rem demand all inputs, because they don't want divide by zero.
1539 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1540 UndefElts, Depth+1);
1541 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1542 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1543 UndefElts2, Depth+1);
1544 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1545
1546 // Output elements are undefined if both are undefined. Consider things
1547 // like undef&0. The result is known zero, not undef.
1548 UndefElts &= UndefElts2;
1549 break;
1550
1551 case Instruction::Call: {
1552 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1553 if (!II) break;
1554 switch (II->getIntrinsicID()) {
1555 default: break;
1556
1557 // Binary vector operations that work column-wise. A dest element is a
1558 // function of the corresponding input elements from the two inputs.
1559 case Intrinsic::x86_sse_sub_ss:
1560 case Intrinsic::x86_sse_mul_ss:
1561 case Intrinsic::x86_sse_min_ss:
1562 case Intrinsic::x86_sse_max_ss:
1563 case Intrinsic::x86_sse2_sub_sd:
1564 case Intrinsic::x86_sse2_mul_sd:
1565 case Intrinsic::x86_sse2_min_sd:
1566 case Intrinsic::x86_sse2_max_sd:
1567 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1568 UndefElts, Depth+1);
1569 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1570 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1571 UndefElts2, Depth+1);
1572 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1573
1574 // If only the low elt is demanded and this is a scalarizable intrinsic,
1575 // scalarize it now.
1576 if (DemandedElts == 1) {
1577 switch (II->getIntrinsicID()) {
1578 default: break;
1579 case Intrinsic::x86_sse_sub_ss:
1580 case Intrinsic::x86_sse_mul_ss:
1581 case Intrinsic::x86_sse2_sub_sd:
1582 case Intrinsic::x86_sse2_mul_sd:
1583 // TODO: Lower MIN/MAX/ABS/etc
1584 Value *LHS = II->getOperand(1);
1585 Value *RHS = II->getOperand(2);
1586 // Extract the element as scalars.
1587 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1588 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1589
1590 switch (II->getIntrinsicID()) {
1591 default: assert(0 && "Case stmts out of sync!");
1592 case Intrinsic::x86_sse_sub_ss:
1593 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001594 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001595 II->getName()), *II);
1596 break;
1597 case Intrinsic::x86_sse_mul_ss:
1598 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001599 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001600 II->getName()), *II);
1601 break;
1602 }
1603
1604 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001605 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1606 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001607 InsertNewInstBefore(New, *II);
1608 AddSoonDeadInstToWorklist(*II, 0);
1609 return New;
1610 }
1611 }
1612
1613 // Output elements are undefined if both are undefined. Consider things
1614 // like undef&0. The result is known zero, not undef.
1615 UndefElts &= UndefElts2;
1616 break;
1617 }
1618 break;
1619 }
1620 }
1621 return MadeChange ? I : 0;
1622}
1623
Dan Gohman45b4e482008-05-19 22:14:15 +00001624
Chris Lattner564a7272003-08-13 19:01:45 +00001625/// AssociativeOpt - Perform an optimization on an associative operator. This
1626/// function is designed to check a chain of associative operators for a
1627/// potential to apply a certain optimization. Since the optimization may be
1628/// applicable if the expression was reassociated, this checks the chain, then
1629/// reassociates the expression as necessary to expose the optimization
1630/// opportunity. This makes use of a special Functor, which must define
1631/// 'shouldApply' and 'apply' methods.
1632///
1633template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001634static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001635 unsigned Opcode = Root.getOpcode();
1636 Value *LHS = Root.getOperand(0);
1637
1638 // Quick check, see if the immediate LHS matches...
1639 if (F.shouldApply(LHS))
1640 return F.apply(Root);
1641
1642 // Otherwise, if the LHS is not of the same opcode as the root, return.
1643 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001644 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001645 // Should we apply this transform to the RHS?
1646 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1647
1648 // If not to the RHS, check to see if we should apply to the LHS...
1649 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1650 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1651 ShouldApply = true;
1652 }
1653
1654 // If the functor wants to apply the optimization to the RHS of LHSI,
1655 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1656 if (ShouldApply) {
1657 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001658
Chris Lattner564a7272003-08-13 19:01:45 +00001659 // Now all of the instructions are in the current basic block, go ahead
1660 // and perform the reassociation.
1661 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1662
1663 // First move the selected RHS to the LHS of the root...
1664 Root.setOperand(0, LHSI->getOperand(1));
1665
1666 // Make what used to be the LHS of the root be the user of the root...
1667 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001668 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001669 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1670 return 0;
1671 }
Chris Lattner65725312004-04-16 18:08:07 +00001672 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001673 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001674 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1675 BasicBlock::iterator ARI = &Root; ++ARI;
1676 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1677 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001678
1679 // Now propagate the ExtraOperand down the chain of instructions until we
1680 // get to LHSI.
1681 while (TmpLHSI != LHSI) {
1682 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001683 // Move the instruction to immediately before the chain we are
1684 // constructing to avoid breaking dominance properties.
1685 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1686 BB->getInstList().insert(ARI, NextLHSI);
1687 ARI = NextLHSI;
1688
Chris Lattner564a7272003-08-13 19:01:45 +00001689 Value *NextOp = NextLHSI->getOperand(1);
1690 NextLHSI->setOperand(1, ExtraOperand);
1691 TmpLHSI = NextLHSI;
1692 ExtraOperand = NextOp;
1693 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001694
Chris Lattner564a7272003-08-13 19:01:45 +00001695 // Now that the instructions are reassociated, have the functor perform
1696 // the transformation...
1697 return F.apply(Root);
1698 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001699
Chris Lattner564a7272003-08-13 19:01:45 +00001700 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1701 }
1702 return 0;
1703}
1704
Dan Gohman844731a2008-05-13 00:00:25 +00001705namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001706
Nick Lewycky02d639f2008-05-23 04:34:58 +00001707// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001708struct AddRHS {
1709 Value *RHS;
1710 AddRHS(Value *rhs) : RHS(rhs) {}
1711 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1712 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001713 return BinaryOperator::CreateShl(Add.getOperand(0),
1714 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001715 }
1716};
1717
1718// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1719// iff C1&C2 == 0
1720struct AddMaskingAnd {
1721 Constant *C2;
1722 AddMaskingAnd(Constant *c) : C2(c) {}
1723 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001724 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001725 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001726 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001727 }
1728 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001729 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001730 }
1731};
1732
Dan Gohman844731a2008-05-13 00:00:25 +00001733}
1734
Chris Lattner6e7ba452005-01-01 16:22:27 +00001735static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001736 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001737 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001738 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001739 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001740
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001741 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00001742 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001743 }
1744
Chris Lattner2eefe512004-04-09 19:05:30 +00001745 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001746 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1747 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001748
Chris Lattner2eefe512004-04-09 19:05:30 +00001749 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1750 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001751 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1752 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001753 }
1754
1755 Value *Op0 = SO, *Op1 = ConstOperand;
1756 if (!ConstIsRHS)
1757 std::swap(Op0, Op1);
1758 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001759 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001760 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001761 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001762 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001763 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001764 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001765 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001766 abort();
1767 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001768 return IC->InsertNewInstBefore(New, I);
1769}
1770
1771// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1772// constant as the other operand, try to fold the binary operator into the
1773// select arguments. This also works for Cast instructions, which obviously do
1774// not have a second operand.
1775static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1776 InstCombiner *IC) {
1777 // Don't modify shared select instructions
1778 if (!SI->hasOneUse()) return 0;
1779 Value *TV = SI->getOperand(1);
1780 Value *FV = SI->getOperand(2);
1781
1782 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001783 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001784 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001785
Chris Lattner6e7ba452005-01-01 16:22:27 +00001786 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1787 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1788
Gabor Greif051a9502008-04-06 20:25:17 +00001789 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1790 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001791 }
1792 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001793}
1794
Chris Lattner4e998b22004-09-29 05:07:12 +00001795
1796/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1797/// node as operand #0, see if we can fold the instruction into the PHI (which
1798/// is only possible if all operands to the PHI are constants).
1799Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1800 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001801 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001802 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001803
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001804 // Check to see if all of the operands of the PHI are constants. If there is
1805 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001806 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001807 BasicBlock *NonConstBB = 0;
1808 for (unsigned i = 0; i != NumPHIValues; ++i)
1809 if (!isa<Constant>(PN->getIncomingValue(i))) {
1810 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001811 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001812 NonConstBB = PN->getIncomingBlock(i);
1813
1814 // If the incoming non-constant value is in I's block, we have an infinite
1815 // loop.
1816 if (NonConstBB == I.getParent())
1817 return 0;
1818 }
1819
1820 // If there is exactly one non-constant value, we can insert a copy of the
1821 // operation in that block. However, if this is a critical edge, we would be
1822 // inserting the computation one some other paths (e.g. inside a loop). Only
1823 // do this if the pred block is unconditionally branching into the phi block.
1824 if (NonConstBB) {
1825 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1826 if (!BI || !BI->isUnconditional()) return 0;
1827 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001828
1829 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001830 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001831 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001832 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001833 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001834
1835 // Next, add all of the operands to the PHI.
1836 if (I.getNumOperands() == 2) {
1837 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001838 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001839 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001840 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001841 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1842 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1843 else
1844 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001845 } else {
1846 assert(PN->getIncomingBlock(i) == NonConstBB);
1847 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001848 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001849 PN->getIncomingValue(i), C, "phitmp",
1850 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001851 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001852 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001853 CI->getPredicate(),
1854 PN->getIncomingValue(i), C, "phitmp",
1855 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001856 else
1857 assert(0 && "Unknown binop!");
1858
Chris Lattnerdbab3862007-03-02 21:28:56 +00001859 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001860 }
1861 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001862 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001863 } else {
1864 CastInst *CI = cast<CastInst>(&I);
1865 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001866 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001867 Value *InV;
1868 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001869 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001870 } else {
1871 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001872 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001873 I.getType(), "phitmp",
1874 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001875 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001876 }
1877 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001878 }
1879 }
1880 return ReplaceInstUsesWith(I, NewPN);
1881}
1882
Chris Lattner2454a2e2008-01-29 06:52:45 +00001883
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001884/// WillNotOverflowSignedAdd - Return true if we can prove that:
1885/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1886/// This basically requires proving that the add in the original type would not
1887/// overflow to change the sign bit or have a carry out.
1888bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1889 // There are different heuristics we can use for this. Here are some simple
1890 // ones.
1891
1892 // Add has the property that adding any two 2's complement numbers can only
1893 // have one carry bit which can change a sign. As such, if LHS and RHS each
1894 // have at least two sign bits, we know that the addition of the two values will
1895 // sign extend fine.
1896 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1897 return true;
1898
1899
1900 // If one of the operands only has one non-zero bit, and if the other operand
1901 // has a known-zero bit in a more significant place than it (not including the
1902 // sign bit) the ripple may go up to and fill the zero, but won't change the
1903 // sign. For example, (X & ~4) + 1.
1904
1905 // TODO: Implement.
1906
1907 return false;
1908}
1909
Chris Lattner2454a2e2008-01-29 06:52:45 +00001910
Chris Lattner7e708292002-06-25 16:13:24 +00001911Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001912 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001913 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001914
Chris Lattner66331a42004-04-10 22:01:55 +00001915 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001916 // X + undef -> undef
1917 if (isa<UndefValue>(RHS))
1918 return ReplaceInstUsesWith(I, RHS);
1919
Chris Lattner66331a42004-04-10 22:01:55 +00001920 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001921 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001922 if (RHSC->isNullValue())
1923 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001924 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001925 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1926 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001927 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001928 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001929
Chris Lattner66331a42004-04-10 22:01:55 +00001930 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001931 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001932 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001933 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001934 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001935 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001936
1937 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1938 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001939 if (!isa<VectorType>(I.getType())) {
1940 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1941 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1942 KnownZero, KnownOne))
1943 return &I;
1944 }
Chris Lattner66331a42004-04-10 22:01:55 +00001945 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001946
1947 if (isa<PHINode>(LHS))
1948 if (Instruction *NV = FoldOpIntoPhi(I))
1949 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001950
Chris Lattner4f637d42006-01-06 17:59:59 +00001951 ConstantInt *XorRHS = 0;
1952 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00001953 if (isa<ConstantInt>(RHSC) &&
1954 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00001955 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001956 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00001957
Zhou Sheng4351c642007-04-02 08:20:41 +00001958 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001959 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1960 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00001961 do {
1962 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00001963 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1964 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001965 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1966 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00001967 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00001968 if (!MaskedValueIsZero(XorLHS,
1969 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00001970 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00001971 break;
Chris Lattner5931c542005-09-24 23:43:33 +00001972 }
1973 }
1974 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00001975 C0080Val = APIntOps::lshr(C0080Val, Size);
1976 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1977 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00001978
Reid Spencer35c38852007-03-28 01:36:16 +00001979 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00001980 // with funny bit widths then this switch statement should be removed. It
1981 // is just here to get the size of the "middle" type back up to something
1982 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00001983 const Type *MiddleType = 0;
1984 switch (Size) {
1985 default: break;
1986 case 32: MiddleType = Type::Int32Ty; break;
1987 case 16: MiddleType = Type::Int16Ty; break;
1988 case 8: MiddleType = Type::Int8Ty; break;
1989 }
1990 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00001991 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00001992 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00001993 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00001994 }
1995 }
Chris Lattner66331a42004-04-10 22:01:55 +00001996 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001997
Nick Lewycky9419ddb2008-05-31 17:59:52 +00001998 if (I.getType() == Type::Int1Ty)
1999 return BinaryOperator::CreateXor(LHS, RHS);
2000
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002001 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002002 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002003 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002004
2005 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2006 if (RHSI->getOpcode() == Instruction::Sub)
2007 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2008 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2009 }
2010 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2011 if (LHSI->getOpcode() == Instruction::Sub)
2012 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2013 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2014 }
Robert Bocchino71698282004-07-27 21:02:21 +00002015 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002016
Chris Lattner5c4afb92002-05-08 22:46:53 +00002017 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002018 // -A + -B --> -(A + B)
2019 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002020 if (LHS->getType()->isIntOrIntVector()) {
2021 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002022 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002023 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002024 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002025 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002026 }
2027
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002028 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002029 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002030
2031 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002032 if (!isa<Constant>(RHS))
2033 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002034 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002035
Misha Brukmanfd939082005-04-21 23:48:37 +00002036
Chris Lattner50af16a2004-11-13 19:50:12 +00002037 ConstantInt *C2;
2038 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2039 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002040 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002041
2042 // X*C1 + X*C2 --> X * (C1+C2)
2043 ConstantInt *C1;
2044 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002045 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002046 }
2047
2048 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002049 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002050 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002051
Chris Lattnere617c9e2007-01-05 02:17:46 +00002052 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002053 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2054 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002055
Chris Lattnerad3448c2003-02-18 19:57:07 +00002056
Chris Lattner564a7272003-08-13 19:01:45 +00002057 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002058 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002059 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2060 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002061
2062 // A+B --> A|B iff A and B have no bits set in common.
2063 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2064 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2065 APInt LHSKnownOne(IT->getBitWidth(), 0);
2066 APInt LHSKnownZero(IT->getBitWidth(), 0);
2067 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2068 if (LHSKnownZero != 0) {
2069 APInt RHSKnownOne(IT->getBitWidth(), 0);
2070 APInt RHSKnownZero(IT->getBitWidth(), 0);
2071 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2072
2073 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002074 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002075 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002076 }
2077 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002078
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002079 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002080 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002081 Value *W, *X, *Y, *Z;
2082 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2083 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2084 if (W != Y) {
2085 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002086 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002087 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002088 std::swap(W, X);
2089 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002090 std::swap(Y, Z);
2091 std::swap(W, X);
2092 }
2093 }
2094
2095 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002096 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002097 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002098 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002099 }
2100 }
2101 }
2102
Chris Lattner6b032052003-10-02 15:11:26 +00002103 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002104 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002105 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002106 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002107
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002108 // (X & FF00) + xx00 -> (X+xx00) & FF00
2109 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002110 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002111 if (Anded == CRHS) {
2112 // See if all bits from the first bit set in the Add RHS up are included
2113 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002114 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002115
2116 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002117 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002118
2119 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002120 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002121
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002122 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2123 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002124 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002125 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002126 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002127 }
2128 }
2129 }
2130
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002131 // Try to fold constant add into select arguments.
2132 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002133 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002134 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002135 }
2136
Reid Spencer1628cec2006-10-26 06:15:43 +00002137 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002138 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002139 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002140 CastInst *CI = dyn_cast<CastInst>(LHS);
2141 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002142 if (!CI) {
2143 CI = dyn_cast<CastInst>(RHS);
2144 Other = LHS;
2145 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002146 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002147 (CI->getType()->getPrimitiveSizeInBits() ==
2148 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002149 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002150 unsigned AS =
2151 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002152 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2153 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002154 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002155 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002156 }
2157 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002158
Chris Lattner42790482007-12-20 01:56:58 +00002159 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002160 {
2161 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2162 Value *Other = RHS;
2163 if (!SI) {
2164 SI = dyn_cast<SelectInst>(RHS);
2165 Other = LHS;
2166 }
Chris Lattner42790482007-12-20 01:56:58 +00002167 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002168 Value *TV = SI->getTrueValue();
2169 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002170 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002171
2172 // Can we fold the add into the argument of the select?
2173 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002174 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2175 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002176 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002177 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2178 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002179 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002180 }
2181 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002182
2183 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2184 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2185 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2186 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002187
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002188 // Check for (add (sext x), y), see if we can merge this into an
2189 // integer add followed by a sext.
2190 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2191 // (add (sext x), cst) --> (sext (add x, cst'))
2192 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2193 Constant *CI =
2194 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2195 if (LHSConv->hasOneUse() &&
2196 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2197 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2198 // Insert the new, smaller add.
2199 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2200 CI, "addconv");
2201 InsertNewInstBefore(NewAdd, I);
2202 return new SExtInst(NewAdd, I.getType());
2203 }
2204 }
2205
2206 // (add (sext x), (sext y)) --> (sext (add int x, y))
2207 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2208 // Only do this if x/y have the same type, if at last one of them has a
2209 // single use (so we don't increase the number of sexts), and if the
2210 // integer add will not overflow.
2211 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2212 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2213 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2214 RHSConv->getOperand(0))) {
2215 // Insert the new integer add.
2216 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2217 RHSConv->getOperand(0),
2218 "addconv");
2219 InsertNewInstBefore(NewAdd, I);
2220 return new SExtInst(NewAdd, I.getType());
2221 }
2222 }
2223 }
2224
2225 // Check for (add double (sitofp x), y), see if we can merge this into an
2226 // integer add followed by a promotion.
2227 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2228 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2229 // ... if the constant fits in the integer value. This is useful for things
2230 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2231 // requires a constant pool load, and generally allows the add to be better
2232 // instcombined.
2233 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2234 Constant *CI =
2235 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2236 if (LHSConv->hasOneUse() &&
2237 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2238 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2239 // Insert the new integer add.
2240 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2241 CI, "addconv");
2242 InsertNewInstBefore(NewAdd, I);
2243 return new SIToFPInst(NewAdd, I.getType());
2244 }
2245 }
2246
2247 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2248 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2249 // Only do this if x/y have the same type, if at last one of them has a
2250 // single use (so we don't increase the number of int->fp conversions),
2251 // and if the integer add will not overflow.
2252 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2253 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2254 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2255 RHSConv->getOperand(0))) {
2256 // Insert the new integer add.
2257 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2258 RHSConv->getOperand(0),
2259 "addconv");
2260 InsertNewInstBefore(NewAdd, I);
2261 return new SIToFPInst(NewAdd, I.getType());
2262 }
2263 }
2264 }
2265
Chris Lattner7e708292002-06-25 16:13:24 +00002266 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002267}
2268
Chris Lattner7e708292002-06-25 16:13:24 +00002269Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002270 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002271
Chris Lattner233f7dc2002-08-12 21:17:25 +00002272 if (Op0 == Op1) // sub X, X -> 0
2273 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002274
Chris Lattner233f7dc2002-08-12 21:17:25 +00002275 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002276 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002277 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002278
Chris Lattnere87597f2004-10-16 18:11:37 +00002279 if (isa<UndefValue>(Op0))
2280 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2281 if (isa<UndefValue>(Op1))
2282 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2283
Chris Lattnerd65460f2003-11-05 01:06:05 +00002284 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2285 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002286 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002287 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002288
Chris Lattnerd65460f2003-11-05 01:06:05 +00002289 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002290 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002291 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002292 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002293
Chris Lattner76b7a062007-01-15 07:02:54 +00002294 // -(X >>u 31) -> (X >>s 31)
2295 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002296 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002297 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002298 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002299 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002300 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002301 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002302 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002303 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002304 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002305 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002306 }
2307 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002308 }
2309 else if (SI->getOpcode() == Instruction::AShr) {
2310 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2311 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002312 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002313 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002314 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002315 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002316 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002317 }
2318 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002319 }
2320 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002321 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002322
2323 // Try to fold constant sub into select arguments.
2324 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002325 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002326 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002327
2328 if (isa<PHINode>(Op0))
2329 if (Instruction *NV = FoldOpIntoPhi(I))
2330 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002331 }
2332
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002333 if (I.getType() == Type::Int1Ty)
2334 return BinaryOperator::CreateXor(Op0, Op1);
2335
Chris Lattner43d84d62005-04-07 16:15:25 +00002336 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2337 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002338 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002339 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002340 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002341 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002342 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002343 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2344 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2345 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002346 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002347 Op1I->getOperand(0));
2348 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002349 }
2350
Chris Lattnerfd059242003-10-15 16:48:29 +00002351 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002352 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2353 // is not used by anyone else...
2354 //
Chris Lattner0517e722004-02-02 20:09:56 +00002355 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002356 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002357 // Swap the two operands of the subexpr...
2358 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2359 Op1I->setOperand(0, IIOp1);
2360 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002361
Chris Lattnera2881962003-02-18 19:28:33 +00002362 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002363 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002364 }
2365
2366 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2367 //
2368 if (Op1I->getOpcode() == Instruction::And &&
2369 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2370 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2371
Chris Lattnerf523d062004-06-09 05:08:07 +00002372 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002373 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2374 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002375 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002376
Reid Spencerac5209e2006-10-16 23:08:08 +00002377 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002378 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002379 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002380 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002381 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002382 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002383 ConstantExpr::getNeg(DivRHS));
2384
Chris Lattnerad3448c2003-02-18 19:57:07 +00002385 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002386 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002387 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002388 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002389 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002390 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002391
2392 // X - ((X / Y) * Y) --> X % Y
2393 if (Op1I->getOpcode() == Instruction::Mul)
2394 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2395 if (Op0 == I->getOperand(0) &&
2396 Op1I->getOperand(1) == I->getOperand(1)) {
2397 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002398 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002399 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002400 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002401 }
Chris Lattner40371712002-05-09 01:29:19 +00002402 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002403 }
Chris Lattnera2881962003-02-18 19:28:33 +00002404
Chris Lattner9919e3d2006-12-02 00:13:08 +00002405 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002406 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002407 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002408 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2409 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2410 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2411 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002412 } else if (Op0I->getOpcode() == Instruction::Sub) {
2413 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002414 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002415 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002416 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002417
Chris Lattner50af16a2004-11-13 19:50:12 +00002418 ConstantInt *C1;
2419 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002420 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002421 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002422
Chris Lattner50af16a2004-11-13 19:50:12 +00002423 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2424 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002425 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002426 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002427 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002428}
2429
Chris Lattnera0141b92007-07-15 20:42:37 +00002430/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2431/// comparison only checks the sign bit. If it only checks the sign bit, set
2432/// TrueIfSigned if the result of the comparison is true when the input value is
2433/// signed.
2434static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2435 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002436 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002437 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2438 TrueIfSigned = true;
2439 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002440 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2441 TrueIfSigned = true;
2442 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002443 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2444 TrueIfSigned = false;
2445 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002446 case ICmpInst::ICMP_UGT:
2447 // True if LHS u> RHS and RHS == high-bit-mask - 1
2448 TrueIfSigned = true;
2449 return RHS->getValue() ==
2450 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2451 case ICmpInst::ICMP_UGE:
2452 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2453 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002454 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002455 default:
2456 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002457 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002458}
2459
Chris Lattner7e708292002-06-25 16:13:24 +00002460Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002461 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002462 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002463
Chris Lattnere87597f2004-10-16 18:11:37 +00002464 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2465 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2466
Chris Lattner233f7dc2002-08-12 21:17:25 +00002467 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002468 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2469 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002470
2471 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002472 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002473 if (SI->getOpcode() == Instruction::Shl)
2474 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002475 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002476 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002477
Zhou Sheng843f07672007-04-19 05:39:12 +00002478 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002479 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2480 if (CI->equalsInt(1)) // X * 1 == X
2481 return ReplaceInstUsesWith(I, Op0);
2482 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002483 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002484
Zhou Sheng97b52c22007-03-29 01:57:21 +00002485 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002486 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002487 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002488 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002489 }
Robert Bocchino71698282004-07-27 21:02:21 +00002490 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002491 if (Op1F->isNullValue())
2492 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002493
Chris Lattnera2881962003-02-18 19:28:33 +00002494 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2495 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002496 // We need a better interface for long double here.
2497 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2498 if (Op1F->isExactlyValue(1.0))
2499 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002500 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002501
2502 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2503 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002504 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002505 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002506 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002507 Op1, "tmp");
2508 InsertNewInstBefore(Add, I);
2509 Value *C1C2 = ConstantExpr::getMul(Op1,
2510 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002511 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002512
2513 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002514
2515 // Try to fold constant mul into select arguments.
2516 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002517 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002518 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002519
2520 if (isa<PHINode>(Op0))
2521 if (Instruction *NV = FoldOpIntoPhi(I))
2522 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002523 }
2524
Chris Lattnera4f445b2003-03-10 23:23:04 +00002525 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2526 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002527 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002528
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002529 if (I.getType() == Type::Int1Ty)
2530 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2531
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002532 // If one of the operands of the multiply is a cast from a boolean value, then
2533 // we know the bool is either zero or one, so this is a 'masking' multiply.
2534 // See if we can simplify things based on how the boolean was originally
2535 // formed.
2536 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002537 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002538 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002539 BoolCast = CI;
2540 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002541 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002542 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002543 BoolCast = CI;
2544 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002545 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002546 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2547 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002548 bool TIS = false;
2549
Reid Spencere4d87aa2006-12-23 06:05:41 +00002550 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002551 // multiply into a shift/and combination.
2552 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002553 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2554 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002555 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002556 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002557 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002558 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002559 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002560 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002561 BoolCast->getOperand(0)->getName()+
2562 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002563
2564 // If the multiply type is not the same as the source type, sign extend
2565 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002566 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002567 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2568 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002569 Instruction::CastOps opcode =
2570 (SrcBits == DstBits ? Instruction::BitCast :
2571 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2572 V = InsertCastBefore(opcode, V, I.getType(), I);
2573 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002574
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002575 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002576 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002577 }
2578 }
2579 }
2580
Chris Lattner7e708292002-06-25 16:13:24 +00002581 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002582}
2583
Reid Spencer1628cec2006-10-26 06:15:43 +00002584/// This function implements the transforms on div instructions that work
2585/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2586/// used by the visitors to those instructions.
2587/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002588Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002589 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002590
Chris Lattner50b2ca42008-02-19 06:12:18 +00002591 // undef / X -> 0 for integer.
2592 // undef / X -> undef for FP (the undef could be a snan).
2593 if (isa<UndefValue>(Op0)) {
2594 if (Op0->getType()->isFPOrFPVector())
2595 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002596 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002597 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002598
2599 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002600 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002601 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002602
Chris Lattner25feae52008-01-28 00:58:18 +00002603 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2604 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002605 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002606 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2607 // the same basic block, then we replace the select with Y, and the
2608 // condition of the select with false (if the cond value is in the same BB).
2609 // If the select has uses other than the div, this allows them to be
2610 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2611 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002612 if (ST->isNullValue()) {
2613 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2614 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002615 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002616 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2617 I.setOperand(1, SI->getOperand(2));
2618 else
2619 UpdateValueUsesWith(SI, SI->getOperand(2));
2620 return &I;
2621 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002622
Chris Lattner25feae52008-01-28 00:58:18 +00002623 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2624 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002625 if (ST->isNullValue()) {
2626 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2627 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002628 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002629 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2630 I.setOperand(1, SI->getOperand(1));
2631 else
2632 UpdateValueUsesWith(SI, SI->getOperand(1));
2633 return &I;
2634 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002635 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002636
Reid Spencer1628cec2006-10-26 06:15:43 +00002637 return 0;
2638}
Misha Brukmanfd939082005-04-21 23:48:37 +00002639
Reid Spencer1628cec2006-10-26 06:15:43 +00002640/// This function implements the transforms common to both integer division
2641/// instructions (udiv and sdiv). It is called by the visitors to those integer
2642/// division instructions.
2643/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002644Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002645 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2646
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002647 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002648 if (Op0 == Op1) {
2649 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2650 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2651 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2652 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2653 }
2654
2655 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2656 return ReplaceInstUsesWith(I, CI);
2657 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002658
Reid Spencer1628cec2006-10-26 06:15:43 +00002659 if (Instruction *Common = commonDivTransforms(I))
2660 return Common;
2661
2662 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2663 // div X, 1 == X
2664 if (RHS->equalsInt(1))
2665 return ReplaceInstUsesWith(I, Op0);
2666
2667 // (X / C1) / C2 -> X / (C1*C2)
2668 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2669 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2670 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002671 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2672 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2673 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002674 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002675 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002676 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002677
Reid Spencerbca0e382007-03-23 20:05:17 +00002678 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002679 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2680 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2681 return R;
2682 if (isa<PHINode>(Op0))
2683 if (Instruction *NV = FoldOpIntoPhi(I))
2684 return NV;
2685 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002686 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002687
Chris Lattnera2881962003-02-18 19:28:33 +00002688 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002689 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002690 if (LHS->equalsInt(0))
2691 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2692
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002693 // It can't be division by zero, hence it must be division by one.
2694 if (I.getType() == Type::Int1Ty)
2695 return ReplaceInstUsesWith(I, Op0);
2696
Reid Spencer1628cec2006-10-26 06:15:43 +00002697 return 0;
2698}
2699
2700Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2701 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2702
2703 // Handle the integer div common cases
2704 if (Instruction *Common = commonIDivTransforms(I))
2705 return Common;
2706
2707 // X udiv C^2 -> X >> C
2708 // Check to see if this is an unsigned division with an exact power of 2,
2709 // if so, convert to a right shift.
2710 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002711 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002712 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002713 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002714 }
2715
2716 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002717 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002718 if (RHSI->getOpcode() == Instruction::Shl &&
2719 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002720 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002721 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002722 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002723 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002724 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002725 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002726 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002727 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002728 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002729 }
2730 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002731 }
2732
Reid Spencer1628cec2006-10-26 06:15:43 +00002733 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2734 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002735 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002736 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002737 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002738 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002739 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002740 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002741 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002742 // Construct the "on true" case of the select
2743 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002744 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002745 Op0, TC, SI->getName()+".t");
2746 TSI = InsertNewInstBefore(TSI, I);
2747
2748 // Construct the "on false" case of the select
2749 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002750 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002751 Op0, FC, SI->getName()+".f");
2752 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002753
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002754 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002755 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002756 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002757 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002758 return 0;
2759}
2760
Reid Spencer1628cec2006-10-26 06:15:43 +00002761Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2762 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2763
2764 // Handle the integer div common cases
2765 if (Instruction *Common = commonIDivTransforms(I))
2766 return Common;
2767
2768 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2769 // sdiv X, -1 == -X
2770 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002771 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002772
2773 // -X/C -> X/-C
2774 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002775 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00002776 }
2777
2778 // If the sign bits of both operands are zero (i.e. we can prove they are
2779 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002780 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002781 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002782 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002783 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002784 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002785 }
2786 }
2787
2788 return 0;
2789}
2790
2791Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2792 return commonDivTransforms(I);
2793}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002794
Reid Spencer0a783f72006-11-02 01:53:59 +00002795/// This function implements the transforms on rem instructions that work
2796/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2797/// is used by the visitors to those instructions.
2798/// @brief Transforms common to all three rem instructions
2799Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002800 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002801
Chris Lattner50b2ca42008-02-19 06:12:18 +00002802 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002803 if (Constant *LHS = dyn_cast<Constant>(Op0))
2804 if (LHS->isNullValue())
2805 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2806
Chris Lattner50b2ca42008-02-19 06:12:18 +00002807 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2808 if (I.getType()->isFPOrFPVector())
2809 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002810 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002811 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002812 if (isa<UndefValue>(Op1))
2813 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002814
2815 // Handle cases involving: rem X, (select Cond, Y, Z)
2816 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2817 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2818 // the same basic block, then we replace the select with Y, and the
2819 // condition of the select with false (if the cond value is in the same
2820 // BB). If the select has uses other than the div, this allows them to be
2821 // simplified also.
2822 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2823 if (ST->isNullValue()) {
2824 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2825 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002826 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002827 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2828 I.setOperand(1, SI->getOperand(2));
2829 else
2830 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002831 return &I;
2832 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002833 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2834 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2835 if (ST->isNullValue()) {
2836 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2837 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002838 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002839 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2840 I.setOperand(1, SI->getOperand(1));
2841 else
2842 UpdateValueUsesWith(SI, SI->getOperand(1));
2843 return &I;
2844 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002845 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002846
Reid Spencer0a783f72006-11-02 01:53:59 +00002847 return 0;
2848}
2849
2850/// This function implements the transforms common to both integer remainder
2851/// instructions (urem and srem). It is called by the visitors to those integer
2852/// remainder instructions.
2853/// @brief Common integer remainder transforms
2854Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2855 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2856
2857 if (Instruction *common = commonRemTransforms(I))
2858 return common;
2859
Chris Lattner857e8cd2004-12-12 21:48:58 +00002860 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002861 // X % 0 == undef, we don't need to preserve faults!
2862 if (RHS->equalsInt(0))
2863 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2864
Chris Lattnera2881962003-02-18 19:28:33 +00002865 if (RHS->equalsInt(1)) // X % 1 == 0
2866 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2867
Chris Lattner97943922006-02-28 05:49:21 +00002868 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2869 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2870 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2871 return R;
2872 } else if (isa<PHINode>(Op0I)) {
2873 if (Instruction *NV = FoldOpIntoPhi(I))
2874 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002875 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002876
2877 // See if we can fold away this rem instruction.
2878 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2879 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2880 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2881 KnownZero, KnownOne))
2882 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002883 }
Chris Lattnera2881962003-02-18 19:28:33 +00002884 }
2885
Reid Spencer0a783f72006-11-02 01:53:59 +00002886 return 0;
2887}
2888
2889Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2890 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2891
2892 if (Instruction *common = commonIRemTransforms(I))
2893 return common;
2894
2895 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2896 // X urem C^2 -> X and C
2897 // Check to see if this is an unsigned remainder with an exact power of 2,
2898 // if so, convert to a bitwise and.
2899 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002900 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002901 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00002902 }
2903
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002904 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002905 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2906 if (RHSI->getOpcode() == Instruction::Shl &&
2907 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002908 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002909 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002910 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002911 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002912 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002913 }
2914 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002915 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002916
Reid Spencer0a783f72006-11-02 01:53:59 +00002917 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2918 // where C1&C2 are powers of two.
2919 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2920 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2921 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2922 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002923 if ((STO->getValue().isPowerOf2()) &&
2924 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002925 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002926 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00002927 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002928 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002929 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00002930 }
2931 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002932 }
2933
Chris Lattner3f5b8772002-05-06 16:14:14 +00002934 return 0;
2935}
2936
Reid Spencer0a783f72006-11-02 01:53:59 +00002937Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2938 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2939
Dan Gohmancff55092007-11-05 23:16:33 +00002940 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002941 if (Instruction *common = commonIRemTransforms(I))
2942 return common;
2943
2944 if (Value *RHSNeg = dyn_castNegVal(Op1))
2945 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002946 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002947 // X % -Y -> X % Y
2948 AddUsesToWorkList(I);
2949 I.setOperand(1, RHSNeg);
2950 return &I;
2951 }
2952
Dan Gohmancff55092007-11-05 23:16:33 +00002953 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002954 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002955 if (I.getType()->isInteger()) {
2956 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2957 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2958 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002959 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00002960 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002961 }
2962
2963 return 0;
2964}
2965
2966Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002967 return commonRemTransforms(I);
2968}
2969
Chris Lattner8b170942002-08-09 23:47:40 +00002970// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002971static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002972 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00002973 if (!isSigned)
2974 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2975 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002976}
2977
2978// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002979static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002980 if (!isSigned)
2981 return C->getValue() == 1; // unsigned
2982
2983 // Calculate 1111111111000000000000
2984 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2985 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002986}
2987
Chris Lattner457dd822004-06-09 07:59:58 +00002988// isOneBitSet - Return true if there is exactly one bit set in the specified
2989// constant.
2990static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002991 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002992}
2993
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002994// isHighOnes - Return true if the constant is of the form 1+0+.
2995// This is the same as lowones(~X).
2996static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002997 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002998}
2999
Reid Spencere4d87aa2006-12-23 06:05:41 +00003000/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003001/// are carefully arranged to allow folding of expressions such as:
3002///
3003/// (A < B) | (A > B) --> (A != B)
3004///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003005/// Note that this is only valid if the first and second predicates have the
3006/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003007///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003008/// Three bits are used to represent the condition, as follows:
3009/// 0 A > B
3010/// 1 A == B
3011/// 2 A < B
3012///
3013/// <=> Value Definition
3014/// 000 0 Always false
3015/// 001 1 A > B
3016/// 010 2 A == B
3017/// 011 3 A >= B
3018/// 100 4 A < B
3019/// 101 5 A != B
3020/// 110 6 A <= B
3021/// 111 7 Always true
3022///
3023static unsigned getICmpCode(const ICmpInst *ICI) {
3024 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003025 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003026 case ICmpInst::ICMP_UGT: return 1; // 001
3027 case ICmpInst::ICMP_SGT: return 1; // 001
3028 case ICmpInst::ICMP_EQ: return 2; // 010
3029 case ICmpInst::ICMP_UGE: return 3; // 011
3030 case ICmpInst::ICMP_SGE: return 3; // 011
3031 case ICmpInst::ICMP_ULT: return 4; // 100
3032 case ICmpInst::ICMP_SLT: return 4; // 100
3033 case ICmpInst::ICMP_NE: return 5; // 101
3034 case ICmpInst::ICMP_ULE: return 6; // 110
3035 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003036 // True -> 7
3037 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003038 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003039 return 0;
3040 }
3041}
3042
Reid Spencere4d87aa2006-12-23 06:05:41 +00003043/// getICmpValue - This is the complement of getICmpCode, which turns an
3044/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003045/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003046/// of predicate to use in new icmp instructions.
3047static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3048 switch (code) {
3049 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003050 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003051 case 1:
3052 if (sign)
3053 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3054 else
3055 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3056 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3057 case 3:
3058 if (sign)
3059 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3060 else
3061 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3062 case 4:
3063 if (sign)
3064 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3065 else
3066 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3067 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3068 case 6:
3069 if (sign)
3070 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3071 else
3072 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003073 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003074 }
3075}
3076
Reid Spencere4d87aa2006-12-23 06:05:41 +00003077static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3078 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3079 (ICmpInst::isSignedPredicate(p1) &&
3080 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3081 (ICmpInst::isSignedPredicate(p2) &&
3082 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3083}
3084
3085namespace {
3086// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3087struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003088 InstCombiner &IC;
3089 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003090 ICmpInst::Predicate pred;
3091 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3092 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3093 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003094 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003095 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3096 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003097 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3098 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003099 return false;
3100 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003101 Instruction *apply(Instruction &Log) const {
3102 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3103 if (ICI->getOperand(0) != LHS) {
3104 assert(ICI->getOperand(1) == LHS);
3105 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003106 }
3107
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003108 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003109 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003110 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003111 unsigned Code;
3112 switch (Log.getOpcode()) {
3113 case Instruction::And: Code = LHSCode & RHSCode; break;
3114 case Instruction::Or: Code = LHSCode | RHSCode; break;
3115 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003116 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003117 }
3118
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003119 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3120 ICmpInst::isSignedPredicate(ICI->getPredicate());
3121
3122 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003123 if (Instruction *I = dyn_cast<Instruction>(RV))
3124 return I;
3125 // Otherwise, it's a constant boolean value...
3126 return IC.ReplaceInstUsesWith(Log, RV);
3127 }
3128};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003129} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003130
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003131// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3132// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003133// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003134Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003135 ConstantInt *OpRHS,
3136 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003137 BinaryOperator &TheAnd) {
3138 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003139 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003140 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003141 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003142
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003143 switch (Op->getOpcode()) {
3144 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003145 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003146 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003147 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003148 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003149 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003150 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003151 }
3152 break;
3153 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003154 if (Together == AndRHS) // (X | C) & C --> C
3155 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003156
Chris Lattner6e7ba452005-01-01 16:22:27 +00003157 if (Op->hasOneUse() && Together != OpRHS) {
3158 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003159 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003160 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003161 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003162 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003163 }
3164 break;
3165 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003166 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003167 // Adding a one to a single bit bit-field should be turned into an XOR
3168 // of the bit. First thing to check is to see if this AND is with a
3169 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003170 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003171
3172 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003173 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003174 // Ok, at this point, we know that we are masking the result of the
3175 // ADD down to exactly one bit. If the constant we are adding has
3176 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003177 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003178
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003179 // Check to see if any bits below the one bit set in AndRHSV are set.
3180 if ((AddRHS & (AndRHSV-1)) == 0) {
3181 // If not, the only thing that can effect the output of the AND is
3182 // the bit specified by AndRHSV. If that bit is set, the effect of
3183 // the XOR is to toggle the bit. If it is clear, then the ADD has
3184 // no effect.
3185 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3186 TheAnd.setOperand(0, X);
3187 return &TheAnd;
3188 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003189 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003190 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003191 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003192 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003193 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003194 }
3195 }
3196 }
3197 }
3198 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003199
3200 case Instruction::Shl: {
3201 // We know that the AND will not produce any of the bits shifted in, so if
3202 // the anded constant includes them, clear them now!
3203 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003204 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003205 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003206 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3207 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003208
Zhou Sheng290bec52007-03-29 08:15:12 +00003209 if (CI->getValue() == ShlMask) {
3210 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003211 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3212 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003213 TheAnd.setOperand(1, CI);
3214 return &TheAnd;
3215 }
3216 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003217 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003218 case Instruction::LShr:
3219 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003220 // We know that the AND will not produce any of the bits shifted in, so if
3221 // the anded constant includes them, clear them now! This only applies to
3222 // unsigned shifts, because a signed shr may bring in set bits!
3223 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003224 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003225 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003226 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3227 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003228
Zhou Sheng290bec52007-03-29 08:15:12 +00003229 if (CI->getValue() == ShrMask) {
3230 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003231 return ReplaceInstUsesWith(TheAnd, Op);
3232 } else if (CI != AndRHS) {
3233 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3234 return &TheAnd;
3235 }
3236 break;
3237 }
3238 case Instruction::AShr:
3239 // Signed shr.
3240 // See if this is shifting in some sign extension, then masking it out
3241 // with an and.
3242 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003243 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003244 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003245 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3246 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003247 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003248 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003249 // Make the argument unsigned.
3250 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003251 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003252 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003253 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003254 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003255 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003256 }
3257 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003258 }
3259 return 0;
3260}
3261
Chris Lattner8b170942002-08-09 23:47:40 +00003262
Chris Lattnera96879a2004-09-29 17:40:11 +00003263/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3264/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003265/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3266/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003267/// insert new instructions.
3268Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003269 bool isSigned, bool Inside,
3270 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003271 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003272 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003273 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003274
Chris Lattnera96879a2004-09-29 17:40:11 +00003275 if (Inside) {
3276 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003277 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003278
Reid Spencere4d87aa2006-12-23 06:05:41 +00003279 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003280 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003281 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003282 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3283 return new ICmpInst(pred, V, Hi);
3284 }
3285
3286 // Emit V-Lo <u Hi-Lo
3287 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003288 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003289 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003290 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3291 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003292 }
3293
3294 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003295 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003296
Reid Spencere4e40032007-03-21 23:19:50 +00003297 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003298 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003299 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003300 ICmpInst::Predicate pred = (isSigned ?
3301 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3302 return new ICmpInst(pred, V, Hi);
3303 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003304
Reid Spencere4e40032007-03-21 23:19:50 +00003305 // Emit V-Lo >u Hi-1-Lo
3306 // Note that Hi has already had one subtracted from it, above.
3307 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003308 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003309 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003310 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3311 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003312}
3313
Chris Lattner7203e152005-09-18 07:22:02 +00003314// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3315// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3316// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3317// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003318static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003319 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003320 uint32_t BitWidth = Val->getType()->getBitWidth();
3321 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003322
3323 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003324 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003325 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003326 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003327 return true;
3328}
3329
Chris Lattner7203e152005-09-18 07:22:02 +00003330/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3331/// where isSub determines whether the operator is a sub. If we can fold one of
3332/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003333///
3334/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3335/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3336/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3337///
3338/// return (A +/- B).
3339///
3340Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003341 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003342 Instruction &I) {
3343 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3344 if (!LHSI || LHSI->getNumOperands() != 2 ||
3345 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3346
3347 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3348
3349 switch (LHSI->getOpcode()) {
3350 default: return 0;
3351 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003352 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003353 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003354 if ((Mask->getValue().countLeadingZeros() +
3355 Mask->getValue().countPopulation()) ==
3356 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003357 break;
3358
3359 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3360 // part, we don't need any explicit masks to take them out of A. If that
3361 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003362 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003363 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003364 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003365 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003366 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003367 break;
3368 }
3369 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003370 return 0;
3371 case Instruction::Or:
3372 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003373 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003374 if ((Mask->getValue().countLeadingZeros() +
3375 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003376 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003377 break;
3378 return 0;
3379 }
3380
3381 Instruction *New;
3382 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003383 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003384 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003385 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003386 return InsertNewInstBefore(New, I);
3387}
3388
Chris Lattner7e708292002-06-25 16:13:24 +00003389Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003390 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003391 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003392
Chris Lattnere87597f2004-10-16 18:11:37 +00003393 if (isa<UndefValue>(Op1)) // X & undef -> 0
3394 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3395
Chris Lattner6e7ba452005-01-01 16:22:27 +00003396 // and X, X = X
3397 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003398 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003399
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003400 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003401 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003402 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003403 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3404 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3405 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003406 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003407 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003408 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003409 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003410 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003411 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003412 } else if (isa<ConstantAggregateZero>(Op1)) {
3413 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003414 }
3415 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003416
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003417 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003418 const APInt& AndRHSMask = AndRHS->getValue();
3419 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003420
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003421 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003422 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003423 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003424 Value *Op0LHS = Op0I->getOperand(0);
3425 Value *Op0RHS = Op0I->getOperand(1);
3426 switch (Op0I->getOpcode()) {
3427 case Instruction::Xor:
3428 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003429 // If the mask is only needed on one incoming arm, push it up.
3430 if (Op0I->hasOneUse()) {
3431 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3432 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003433 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003434 Op0RHS->getName()+".masked");
3435 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003436 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003437 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003438 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003439 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003440 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3441 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003442 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003443 Op0LHS->getName()+".masked");
3444 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003445 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003446 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3447 }
3448 }
3449
Chris Lattner6e7ba452005-01-01 16:22:27 +00003450 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003451 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003452 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3453 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3454 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3455 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003456 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003457 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003458 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003459 break;
3460
3461 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003462 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3463 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3464 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3465 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003466 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003467 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003468 }
3469
Chris Lattner58403262003-07-23 19:25:52 +00003470 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003471 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003472 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003473 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003474 // If this is an integer truncation or change from signed-to-unsigned, and
3475 // if the source is an and/or with immediate, transform it. This
3476 // frequently occurs for bitfield accesses.
3477 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003478 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003479 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003480 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003481 if (CastOp->getOpcode() == Instruction::And) {
3482 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003483 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3484 // This will fold the two constants together, which may allow
3485 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003486 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003487 CastOp->getOperand(0), I.getType(),
3488 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003489 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003490 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003491 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003492 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003493 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003494 } else if (CastOp->getOpcode() == Instruction::Or) {
3495 // Change: and (cast (or X, C1) to T), C2
3496 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003497 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003498 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3499 return ReplaceInstUsesWith(I, AndRHS);
3500 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003501 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003502 }
Chris Lattner06782f82003-07-23 19:36:21 +00003503 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003504
3505 // Try to fold constant and into select arguments.
3506 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003507 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003508 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003509 if (isa<PHINode>(Op0))
3510 if (Instruction *NV = FoldOpIntoPhi(I))
3511 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003512 }
3513
Chris Lattner8d969642003-03-10 23:06:50 +00003514 Value *Op0NotVal = dyn_castNotVal(Op0);
3515 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003516
Chris Lattner5b62aa72004-06-18 06:07:51 +00003517 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3518 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3519
Misha Brukmancb6267b2004-07-30 12:50:08 +00003520 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003521 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003522 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003523 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003524 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003525 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003526 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003527
3528 {
Chris Lattner003b6202007-06-15 05:58:24 +00003529 Value *A = 0, *B = 0, *C = 0, *D = 0;
3530 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003531 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3532 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003533
3534 // (A|B) & ~(A&B) -> A^B
3535 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3536 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003537 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003538 }
3539 }
3540
3541 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003542 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3543 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003544
3545 // ~(A&B) & (A|B) -> A^B
3546 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3547 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003548 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003549 }
3550 }
Chris Lattner64daab52006-04-01 08:03:55 +00003551
3552 if (Op0->hasOneUse() &&
3553 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3554 if (A == Op1) { // (A^B)&A -> A&(A^B)
3555 I.swapOperands(); // Simplify below
3556 std::swap(Op0, Op1);
3557 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3558 cast<BinaryOperator>(Op0)->swapOperands();
3559 I.swapOperands(); // Simplify below
3560 std::swap(Op0, Op1);
3561 }
3562 }
3563 if (Op1->hasOneUse() &&
3564 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3565 if (B == Op0) { // B&(A^B) -> B&(B^A)
3566 cast<BinaryOperator>(Op1)->swapOperands();
3567 std::swap(A, B);
3568 }
3569 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003570 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003571 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003572 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003573 }
3574 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003575 }
3576
Reid Spencere4d87aa2006-12-23 06:05:41 +00003577 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3578 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3579 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003580 return R;
3581
Chris Lattner955f3312004-09-28 21:48:02 +00003582 Value *LHSVal, *RHSVal;
3583 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003584 ICmpInst::Predicate LHSCC, RHSCC;
3585 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3586 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3587 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3588 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3589 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3590 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3591 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003592 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3593
3594 // Don't try to fold ICMP_SLT + ICMP_ULT.
3595 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3596 ICmpInst::isSignedPredicate(LHSCC) ==
3597 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003598 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003599 ICmpInst::Predicate GT;
3600 if (ICmpInst::isSignedPredicate(LHSCC) ||
3601 (ICmpInst::isEquality(LHSCC) &&
3602 ICmpInst::isSignedPredicate(RHSCC)))
3603 GT = ICmpInst::ICMP_SGT;
3604 else
3605 GT = ICmpInst::ICMP_UGT;
3606
Reid Spencere4d87aa2006-12-23 06:05:41 +00003607 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3608 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003609 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003610 std::swap(LHS, RHS);
3611 std::swap(LHSCst, RHSCst);
3612 std::swap(LHSCC, RHSCC);
3613 }
3614
Reid Spencere4d87aa2006-12-23 06:05:41 +00003615 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003616 // comparing a value against two constants and and'ing the result
3617 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003618 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3619 // (from the FoldICmpLogical check above), that the two constants
3620 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003621 assert(LHSCst != RHSCst && "Compares not folded above?");
3622
3623 switch (LHSCC) {
3624 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003625 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003626 switch (RHSCC) {
3627 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003628 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3629 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3630 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003631 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003632 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3633 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3634 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003635 return ReplaceInstUsesWith(I, LHS);
3636 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003637 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003638 switch (RHSCC) {
3639 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003640 case ICmpInst::ICMP_ULT:
3641 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3642 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3643 break; // (X != 13 & X u< 15) -> no change
3644 case ICmpInst::ICMP_SLT:
3645 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3646 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3647 break; // (X != 13 & X s< 15) -> no change
3648 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3649 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3650 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003651 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003652 case ICmpInst::ICMP_NE:
3653 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003654 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003655 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00003656 LHSVal->getName()+".off");
3657 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003658 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3659 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003660 }
3661 break; // (X != 13 & X != 15) -> no change
3662 }
3663 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003664 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003665 switch (RHSCC) {
3666 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003667 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3668 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003669 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003670 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3671 break;
3672 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3673 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003674 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003675 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3676 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003677 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003678 break;
3679 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003680 switch (RHSCC) {
3681 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003682 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3683 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003684 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003685 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3686 break;
3687 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3688 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003689 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003690 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3691 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003692 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003693 break;
3694 case ICmpInst::ICMP_UGT:
3695 switch (RHSCC) {
3696 default: assert(0 && "Unknown integer condition code!");
3697 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3698 return ReplaceInstUsesWith(I, LHS);
3699 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3700 return ReplaceInstUsesWith(I, RHS);
3701 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3702 break;
3703 case ICmpInst::ICMP_NE:
3704 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3705 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3706 break; // (X u> 13 & X != 15) -> no change
3707 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3708 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3709 true, I);
3710 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3711 break;
3712 }
3713 break;
3714 case ICmpInst::ICMP_SGT:
3715 switch (RHSCC) {
3716 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003717 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003718 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3719 return ReplaceInstUsesWith(I, RHS);
3720 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3721 break;
3722 case ICmpInst::ICMP_NE:
3723 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3724 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3725 break; // (X s> 13 & X != 15) -> no change
3726 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3727 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3728 true, I);
3729 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3730 break;
3731 }
3732 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003733 }
3734 }
3735 }
3736
Chris Lattner6fc205f2006-05-05 06:39:07 +00003737 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003738 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3739 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3740 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3741 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003742 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003743 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003744 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3745 I.getType(), TD) &&
3746 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3747 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003748 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003749 Op1C->getOperand(0),
3750 I.getName());
3751 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003752 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003753 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003754 }
Chris Lattnere511b742006-11-14 07:46:50 +00003755
3756 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003757 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3758 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3759 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003760 SI0->getOperand(1) == SI1->getOperand(1) &&
3761 (SI0->hasOneUse() || SI1->hasOneUse())) {
3762 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003763 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00003764 SI1->getOperand(0),
3765 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003766 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00003767 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003768 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003769 }
3770
Chris Lattner99c65742007-10-24 05:38:08 +00003771 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3772 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3773 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3774 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3775 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3776 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3777 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3778 // If either of the constants are nans, then the whole thing returns
3779 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003780 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003781 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3782 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3783 RHS->getOperand(0));
3784 }
3785 }
3786 }
3787
Chris Lattner7e708292002-06-25 16:13:24 +00003788 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003789}
3790
Chris Lattnerafe91a52006-06-15 19:07:26 +00003791/// CollectBSwapParts - Look to see if the specified value defines a single byte
3792/// in the result. If it does, and if the specified byte hasn't been filled in
3793/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003794static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003795 Instruction *I = dyn_cast<Instruction>(V);
3796 if (I == 0) return true;
3797
3798 // If this is an or instruction, it is an inner node of the bswap.
3799 if (I->getOpcode() == Instruction::Or)
3800 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3801 CollectBSwapParts(I->getOperand(1), ByteValues);
3802
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003803 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003804 // If this is a shift by a constant int, and it is "24", then its operand
3805 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003806 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003807 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003808 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003809 8*(ByteValues.size()-1))
3810 return true;
3811
3812 unsigned DestNo;
3813 if (I->getOpcode() == Instruction::Shl) {
3814 // X << 24 defines the top byte with the lowest of the input bytes.
3815 DestNo = ByteValues.size()-1;
3816 } else {
3817 // X >>u 24 defines the low byte with the highest of the input bytes.
3818 DestNo = 0;
3819 }
3820
3821 // If the destination byte value is already defined, the values are or'd
3822 // together, which isn't a bswap (unless it's an or of the same bits).
3823 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3824 return true;
3825 ByteValues[DestNo] = I->getOperand(0);
3826 return false;
3827 }
3828
3829 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3830 // don't have this.
3831 Value *Shift = 0, *ShiftLHS = 0;
3832 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3833 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3834 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3835 return true;
3836 Instruction *SI = cast<Instruction>(Shift);
3837
3838 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003839 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3840 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003841 return true;
3842
3843 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3844 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003845 if (AndAmt->getValue().getActiveBits() > 64)
3846 return true;
3847 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003848 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003849 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003850 break;
3851 // Unknown mask for bswap.
3852 if (DestByte == ByteValues.size()) return true;
3853
Reid Spencerb83eb642006-10-20 07:07:24 +00003854 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003855 unsigned SrcByte;
3856 if (SI->getOpcode() == Instruction::Shl)
3857 SrcByte = DestByte - ShiftBytes;
3858 else
3859 SrcByte = DestByte + ShiftBytes;
3860
3861 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3862 if (SrcByte != ByteValues.size()-DestByte-1)
3863 return true;
3864
3865 // If the destination byte value is already defined, the values are or'd
3866 // together, which isn't a bswap (unless it's an or of the same bits).
3867 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3868 return true;
3869 ByteValues[DestByte] = SI->getOperand(0);
3870 return false;
3871}
3872
3873/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3874/// If so, insert the new bswap intrinsic and return it.
3875Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003876 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3877 if (!ITy || ITy->getBitWidth() % 16)
3878 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003879
3880 /// ByteValues - For each byte of the result, we keep track of which value
3881 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003882 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003883 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003884
3885 // Try to find all the pieces corresponding to the bswap.
3886 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3887 CollectBSwapParts(I.getOperand(1), ByteValues))
3888 return 0;
3889
3890 // Check to see if all of the bytes come from the same value.
3891 Value *V = ByteValues[0];
3892 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3893
3894 // Check to make sure that all of the bytes come from the same value.
3895 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3896 if (ByteValues[i] != V)
3897 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003898 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003899 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003900 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00003901 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003902}
3903
3904
Chris Lattner7e708292002-06-25 16:13:24 +00003905Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003906 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003907 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003908
Chris Lattner42593e62007-03-24 23:56:43 +00003909 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003910 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003911
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003912 // or X, X = X
3913 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003914 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003915
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003916 // See if we can simplify any instructions used by the instruction whose sole
3917 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003918 if (!isa<VectorType>(I.getType())) {
3919 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3920 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3921 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3922 KnownZero, KnownOne))
3923 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003924 } else if (isa<ConstantAggregateZero>(Op1)) {
3925 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3926 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3927 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3928 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003929 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003930
3931
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003932
Chris Lattner3f5b8772002-05-06 16:14:14 +00003933 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003934 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003935 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003936 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3937 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003938 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003939 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003940 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003941 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003942 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003943 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003944
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003945 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3946 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003947 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003948 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003949 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003950 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003951 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003952 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003953
3954 // Try to fold constant and into select arguments.
3955 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003956 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003957 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003958 if (isa<PHINode>(Op0))
3959 if (Instruction *NV = FoldOpIntoPhi(I))
3960 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003961 }
3962
Chris Lattner4f637d42006-01-06 17:59:59 +00003963 Value *A = 0, *B = 0;
3964 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003965
3966 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3967 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3968 return ReplaceInstUsesWith(I, Op1);
3969 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3970 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3971 return ReplaceInstUsesWith(I, Op0);
3972
Chris Lattner6423d4c2006-07-10 20:25:24 +00003973 // (A | B) | C and A | (B | C) -> bswap if possible.
3974 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003975 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003976 match(Op1, m_Or(m_Value(), m_Value())) ||
3977 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3978 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003979 if (Instruction *BSwap = MatchBSwap(I))
3980 return BSwap;
3981 }
3982
Chris Lattner6e4c6492005-05-09 04:58:36 +00003983 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3984 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003985 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003986 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00003987 InsertNewInstBefore(NOr, I);
3988 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003989 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003990 }
3991
3992 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3993 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003994 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003995 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00003996 InsertNewInstBefore(NOr, I);
3997 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003998 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003999 }
4000
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004001 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004002 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004003 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4004 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004005 Value *V1 = 0, *V2 = 0, *V3 = 0;
4006 C1 = dyn_cast<ConstantInt>(C);
4007 C2 = dyn_cast<ConstantInt>(D);
4008 if (C1 && C2) { // (A & C1)|(B & C2)
4009 // If we have: ((V + N) & C1) | (V & C2)
4010 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4011 // replace with V+N.
4012 if (C1->getValue() == ~C2->getValue()) {
4013 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4014 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4015 // Add commutes, try both ways.
4016 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4017 return ReplaceInstUsesWith(I, A);
4018 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4019 return ReplaceInstUsesWith(I, A);
4020 }
4021 // Or commutes, try both ways.
4022 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4023 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4024 // Add commutes, try both ways.
4025 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4026 return ReplaceInstUsesWith(I, B);
4027 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4028 return ReplaceInstUsesWith(I, B);
4029 }
4030 }
Chris Lattner044e5332007-04-08 08:01:49 +00004031 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004032 }
4033
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004034 // Check to see if we have any common things being and'ed. If so, find the
4035 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004036 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4037 if (A == B) // (A & C)|(A & D) == A & (C|D)
4038 V1 = A, V2 = C, V3 = D;
4039 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4040 V1 = A, V2 = B, V3 = C;
4041 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4042 V1 = C, V2 = A, V3 = D;
4043 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4044 V1 = C, V2 = A, V3 = B;
4045
4046 if (V1) {
4047 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004048 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4049 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004050 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004051 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004052 }
Chris Lattnere511b742006-11-14 07:46:50 +00004053
4054 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004055 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4056 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4057 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004058 SI0->getOperand(1) == SI1->getOperand(1) &&
4059 (SI0->hasOneUse() || SI1->hasOneUse())) {
4060 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004061 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004062 SI1->getOperand(0),
4063 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004064 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004065 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004066 }
4067 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004068
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004069 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4070 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004071 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004072 } else {
4073 A = 0;
4074 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004075 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004076 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4077 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004078 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004079
Misha Brukmancb6267b2004-07-30 12:50:08 +00004080 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004081 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004082 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004083 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004084 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004085 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004086 }
Chris Lattnera2881962003-02-18 19:28:33 +00004087
Reid Spencere4d87aa2006-12-23 06:05:41 +00004088 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4089 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4090 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004091 return R;
4092
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004093 Value *LHSVal, *RHSVal;
4094 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004095 ICmpInst::Predicate LHSCC, RHSCC;
4096 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4097 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4098 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4099 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4100 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4101 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4102 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004103 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4104 // We can't fold (ugt x, C) | (sgt x, C2).
4105 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004106 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004107 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004108 bool NeedsSwap;
4109 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004110 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004111 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004112 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004113
4114 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004115 std::swap(LHS, RHS);
4116 std::swap(LHSCst, RHSCst);
4117 std::swap(LHSCC, RHSCC);
4118 }
4119
Reid Spencere4d87aa2006-12-23 06:05:41 +00004120 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004121 // comparing a value against two constants and or'ing the result
4122 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004123 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4124 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004125 // equal.
4126 assert(LHSCst != RHSCst && "Compares not folded above?");
4127
4128 switch (LHSCC) {
4129 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004130 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004131 switch (RHSCC) {
4132 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004133 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004134 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4135 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004136 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004137 LHSVal->getName()+".off");
4138 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004139 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004140 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004141 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004142 break; // (X == 13 | X == 15) -> no change
4143 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4144 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004145 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004146 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4147 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4148 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004149 return ReplaceInstUsesWith(I, RHS);
4150 }
4151 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004152 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004153 switch (RHSCC) {
4154 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004155 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4156 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4157 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004158 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004159 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4160 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4161 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004162 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004163 }
4164 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004165 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004166 switch (RHSCC) {
4167 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004168 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004169 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004170 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004171 // If RHSCst is [us]MAXINT, it is always false. Not handling
4172 // this can cause overflow.
4173 if (RHSCst->isMaxValue(false))
4174 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004175 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4176 false, I);
4177 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4178 break;
4179 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4180 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004181 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004182 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4183 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004184 }
4185 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004186 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004187 switch (RHSCC) {
4188 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004189 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4190 break;
4191 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004192 // If RHSCst is [us]MAXINT, it is always false. Not handling
4193 // this can cause overflow.
4194 if (RHSCst->isMaxValue(true))
4195 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004196 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4197 false, I);
4198 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4199 break;
4200 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4201 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4202 return ReplaceInstUsesWith(I, RHS);
4203 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4204 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004205 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004206 break;
4207 case ICmpInst::ICMP_UGT:
4208 switch (RHSCC) {
4209 default: assert(0 && "Unknown integer condition code!");
4210 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4211 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4212 return ReplaceInstUsesWith(I, LHS);
4213 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4214 break;
4215 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4216 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004217 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004218 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4219 break;
4220 }
4221 break;
4222 case ICmpInst::ICMP_SGT:
4223 switch (RHSCC) {
4224 default: assert(0 && "Unknown integer condition code!");
4225 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4226 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4227 return ReplaceInstUsesWith(I, LHS);
4228 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4229 break;
4230 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4231 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004232 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004233 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4234 break;
4235 }
4236 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004237 }
4238 }
4239 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004240
4241 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004242 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004243 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004244 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004245 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4246 !isa<ICmpInst>(Op1C->getOperand(0))) {
4247 const Type *SrcTy = Op0C->getOperand(0)->getType();
4248 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4249 // Only do this if the casts both really cause code to be
4250 // generated.
4251 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4252 I.getType(), TD) &&
4253 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4254 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004255 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004256 Op1C->getOperand(0),
4257 I.getName());
4258 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004259 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004260 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004261 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004262 }
Chris Lattner99c65742007-10-24 05:38:08 +00004263 }
4264
4265
4266 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4267 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4268 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4269 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004270 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4271 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004272 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4273 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4274 // If either of the constants are nans, then the whole thing returns
4275 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004276 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004277 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4278
4279 // Otherwise, no need to compare the two constants, compare the
4280 // rest.
4281 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4282 RHS->getOperand(0));
4283 }
4284 }
4285 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004286
Chris Lattner7e708292002-06-25 16:13:24 +00004287 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004288}
4289
Dan Gohman844731a2008-05-13 00:00:25 +00004290namespace {
4291
Chris Lattnerc317d392004-02-16 01:20:27 +00004292// XorSelf - Implements: X ^ X --> 0
4293struct XorSelf {
4294 Value *RHS;
4295 XorSelf(Value *rhs) : RHS(rhs) {}
4296 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4297 Instruction *apply(BinaryOperator &Xor) const {
4298 return &Xor;
4299 }
4300};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004301
Dan Gohman844731a2008-05-13 00:00:25 +00004302}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004303
Chris Lattner7e708292002-06-25 16:13:24 +00004304Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004305 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004306 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004307
Evan Chengd34af782008-03-25 20:07:13 +00004308 if (isa<UndefValue>(Op1)) {
4309 if (isa<UndefValue>(Op0))
4310 // Handle undef ^ undef -> 0 special case. This is a common
4311 // idiom (misuse).
4312 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004313 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004314 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004315
Chris Lattnerc317d392004-02-16 01:20:27 +00004316 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4317 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004318 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004319 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004320 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004321
4322 // See if we can simplify any instructions used by the instruction whose sole
4323 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004324 if (!isa<VectorType>(I.getType())) {
4325 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4326 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4327 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4328 KnownZero, KnownOne))
4329 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004330 } else if (isa<ConstantAggregateZero>(Op1)) {
4331 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004332 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004333
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004334 // Is this a ~ operation?
4335 if (Value *NotOp = dyn_castNotVal(&I)) {
4336 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4337 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4338 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4339 if (Op0I->getOpcode() == Instruction::And ||
4340 Op0I->getOpcode() == Instruction::Or) {
4341 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4342 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4343 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004344 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004345 Op0I->getOperand(1)->getName()+".not");
4346 InsertNewInstBefore(NotY, I);
4347 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004348 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004349 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004350 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004351 }
4352 }
4353 }
4354 }
4355
4356
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004357 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004358 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4359 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4360 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004361 return new ICmpInst(ICI->getInversePredicate(),
4362 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004363
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004364 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4365 return new FCmpInst(FCI->getInversePredicate(),
4366 FCI->getOperand(0), FCI->getOperand(1));
4367 }
4368
Nick Lewycky517e1f52008-05-31 19:01:33 +00004369 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4370 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4371 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4372 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4373 Instruction::CastOps Opcode = Op0C->getOpcode();
4374 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4375 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4376 Op0C->getDestTy())) {
4377 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4378 CI->getOpcode(), CI->getInversePredicate(),
4379 CI->getOperand(0), CI->getOperand(1)), I);
4380 NewCI->takeName(CI);
4381 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4382 }
4383 }
4384 }
4385 }
4386 }
4387
Reid Spencere4d87aa2006-12-23 06:05:41 +00004388 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004389 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004390 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4391 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004392 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4393 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004394 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004395 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004396 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004397
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004398 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004399 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004400 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004401 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004402 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004403 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004404 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004405 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004406 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004407 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004408 // (X + C) ^ signbit -> (X + C + signbit)
4409 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004410 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004411
Chris Lattner7c4049c2004-01-12 19:35:11 +00004412 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004413 } else if (Op0I->getOpcode() == Instruction::Or) {
4414 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004415 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004416 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4417 // Anything in both C1 and C2 is known to be zero, remove it from
4418 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004419 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004420 NewRHS = ConstantExpr::getAnd(NewRHS,
4421 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004422 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004423 I.setOperand(0, Op0I->getOperand(0));
4424 I.setOperand(1, NewRHS);
4425 return &I;
4426 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004427 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004428 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004429 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004430
4431 // Try to fold constant and into select arguments.
4432 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004433 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004434 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004435 if (isa<PHINode>(Op0))
4436 if (Instruction *NV = FoldOpIntoPhi(I))
4437 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004438 }
4439
Chris Lattner8d969642003-03-10 23:06:50 +00004440 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004441 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004442 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004443
Chris Lattner8d969642003-03-10 23:06:50 +00004444 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004445 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004446 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004447
Chris Lattner318bf792007-03-18 22:51:34 +00004448
4449 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4450 if (Op1I) {
4451 Value *A, *B;
4452 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4453 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004454 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004455 I.swapOperands();
4456 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004457 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004458 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004459 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004460 }
Chris Lattner318bf792007-03-18 22:51:34 +00004461 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4462 if (Op0 == A) // A^(A^B) == B
4463 return ReplaceInstUsesWith(I, B);
4464 else if (Op0 == B) // A^(B^A) == B
4465 return ReplaceInstUsesWith(I, A);
4466 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004467 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004468 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004469 std::swap(A, B);
4470 }
Chris Lattner318bf792007-03-18 22:51:34 +00004471 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004472 I.swapOperands(); // Simplified below.
4473 std::swap(Op0, Op1);
4474 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004475 }
Chris Lattner318bf792007-03-18 22:51:34 +00004476 }
4477
4478 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4479 if (Op0I) {
4480 Value *A, *B;
4481 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4482 if (A == Op1) // (B|A)^B == (A|B)^B
4483 std::swap(A, B);
4484 if (B == Op1) { // (A|B)^B == A & ~B
4485 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004486 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4487 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004488 }
Chris Lattner318bf792007-03-18 22:51:34 +00004489 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4490 if (Op1 == A) // (A^B)^A == B
4491 return ReplaceInstUsesWith(I, B);
4492 else if (Op1 == B) // (B^A)^A == B
4493 return ReplaceInstUsesWith(I, A);
4494 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4495 if (A == Op1) // (A&B)^A -> (B&A)^A
4496 std::swap(A, B);
4497 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004498 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004499 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004500 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4501 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004502 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004503 }
Chris Lattner318bf792007-03-18 22:51:34 +00004504 }
4505
4506 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4507 if (Op0I && Op1I && Op0I->isShift() &&
4508 Op0I->getOpcode() == Op1I->getOpcode() &&
4509 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4510 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4511 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004512 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004513 Op1I->getOperand(0),
4514 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004515 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004516 Op1I->getOperand(1));
4517 }
4518
4519 if (Op0I && Op1I) {
4520 Value *A, *B, *C, *D;
4521 // (A & B)^(A | B) -> A ^ B
4522 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4523 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4524 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004525 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004526 }
4527 // (A | B)^(A & B) -> A ^ B
4528 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4529 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4530 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004531 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004532 }
4533
4534 // (A & B)^(C & D)
4535 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4536 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4537 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4538 // (X & Y)^(X & Y) -> (Y^Z) & X
4539 Value *X = 0, *Y = 0, *Z = 0;
4540 if (A == C)
4541 X = A, Y = B, Z = D;
4542 else if (A == D)
4543 X = A, Y = B, Z = C;
4544 else if (B == C)
4545 X = B, Y = A, Z = D;
4546 else if (B == D)
4547 X = B, Y = A, Z = C;
4548
4549 if (X) {
4550 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004551 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4552 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004553 }
4554 }
4555 }
4556
Reid Spencere4d87aa2006-12-23 06:05:41 +00004557 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4558 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4559 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004560 return R;
4561
Chris Lattner6fc205f2006-05-05 06:39:07 +00004562 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004563 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004564 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004565 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4566 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004567 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004568 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004569 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4570 I.getType(), TD) &&
4571 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4572 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004573 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004574 Op1C->getOperand(0),
4575 I.getName());
4576 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004577 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004578 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004579 }
Chris Lattner99c65742007-10-24 05:38:08 +00004580 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00004581
Chris Lattner7e708292002-06-25 16:13:24 +00004582 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004583}
4584
Chris Lattnera96879a2004-09-29 17:40:11 +00004585/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4586/// overflowed for this type.
4587static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004588 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004589 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004590
Reid Spencere4e40032007-03-21 23:19:50 +00004591 if (IsSigned)
4592 if (In2->getValue().isNegative())
4593 return Result->getValue().sgt(In1->getValue());
4594 else
4595 return Result->getValue().slt(In1->getValue());
4596 else
4597 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004598}
4599
Chris Lattner574da9b2005-01-13 20:14:25 +00004600/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4601/// code necessary to compute the offset from the base pointer (without adding
4602/// in the base pointer). Return the result as a signed integer of intptr size.
4603static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4604 TargetData &TD = IC.getTargetData();
4605 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004606 const Type *IntPtrTy = TD.getIntPtrType();
4607 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004608
4609 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004610 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004611 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004612
Gabor Greif177dd3f2008-06-12 21:37:33 +00004613 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4614 ++i, ++GTI) {
4615 Value *Op = *i;
Duncan Sands514ab342007-11-01 20:53:16 +00004616 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004617 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4618 if (OpC->isZero()) continue;
4619
4620 // Handle a struct index, which adds its field offset to the pointer.
4621 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4622 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4623
4624 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4625 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004626 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004627 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004628 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004629 ConstantInt::get(IntPtrTy, Size),
4630 GEP->getName()+".offs"), I);
4631 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004632 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004633
4634 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4635 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4636 Scale = ConstantExpr::getMul(OC, Scale);
4637 if (Constant *RC = dyn_cast<Constant>(Result))
4638 Result = ConstantExpr::getAdd(RC, Scale);
4639 else {
4640 // Emit an add instruction.
4641 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004642 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004643 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004644 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004645 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004646 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004647 // Convert to correct type.
4648 if (Op->getType() != IntPtrTy) {
4649 if (Constant *OpC = dyn_cast<Constant>(Op))
4650 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4651 else
4652 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4653 Op->getName()+".c"), I);
4654 }
4655 if (Size != 1) {
4656 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4657 if (Constant *OpC = dyn_cast<Constant>(Op))
4658 Op = ConstantExpr::getMul(OpC, Scale);
4659 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004660 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004661 GEP->getName()+".idx"), I);
4662 }
4663
4664 // Emit an add instruction.
4665 if (isa<Constant>(Op) && isa<Constant>(Result))
4666 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4667 cast<Constant>(Result));
4668 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004669 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004670 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004671 }
4672 return Result;
4673}
4674
Chris Lattner10c0d912008-04-22 02:53:33 +00004675
4676/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4677/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4678/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4679/// complex, and scales are involved. The above expression would also be legal
4680/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4681/// later form is less amenable to optimization though, and we are allowed to
4682/// generate the first by knowing that pointer arithmetic doesn't overflow.
4683///
4684/// If we can't emit an optimized form for this expression, this returns null.
4685///
4686static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4687 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00004688 TargetData &TD = IC.getTargetData();
4689 gep_type_iterator GTI = gep_type_begin(GEP);
4690
4691 // Check to see if this gep only has a single variable index. If so, and if
4692 // any constant indices are a multiple of its scale, then we can compute this
4693 // in terms of the scale of the variable index. For example, if the GEP
4694 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4695 // because the expression will cross zero at the same point.
4696 unsigned i, e = GEP->getNumOperands();
4697 int64_t Offset = 0;
4698 for (i = 1; i != e; ++i, ++GTI) {
4699 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4700 // Compute the aggregate offset of constant indices.
4701 if (CI->isZero()) continue;
4702
4703 // Handle a struct index, which adds its field offset to the pointer.
4704 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4705 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4706 } else {
4707 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4708 Offset += Size*CI->getSExtValue();
4709 }
4710 } else {
4711 // Found our variable index.
4712 break;
4713 }
4714 }
4715
4716 // If there are no variable indices, we must have a constant offset, just
4717 // evaluate it the general way.
4718 if (i == e) return 0;
4719
4720 Value *VariableIdx = GEP->getOperand(i);
4721 // Determine the scale factor of the variable element. For example, this is
4722 // 4 if the variable index is into an array of i32.
4723 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4724
4725 // Verify that there are no other variable indices. If so, emit the hard way.
4726 for (++i, ++GTI; i != e; ++i, ++GTI) {
4727 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4728 if (!CI) return 0;
4729
4730 // Compute the aggregate offset of constant indices.
4731 if (CI->isZero()) continue;
4732
4733 // Handle a struct index, which adds its field offset to the pointer.
4734 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4735 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4736 } else {
4737 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4738 Offset += Size*CI->getSExtValue();
4739 }
4740 }
4741
4742 // Okay, we know we have a single variable index, which must be a
4743 // pointer/array/vector index. If there is no offset, life is simple, return
4744 // the index.
4745 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4746 if (Offset == 0) {
4747 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4748 // we don't need to bother extending: the extension won't affect where the
4749 // computation crosses zero.
4750 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4751 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4752 VariableIdx->getNameStart(), &I);
4753 return VariableIdx;
4754 }
4755
4756 // Otherwise, there is an index. The computation we will do will be modulo
4757 // the pointer size, so get it.
4758 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4759
4760 Offset &= PtrSizeMask;
4761 VariableScale &= PtrSizeMask;
4762
4763 // To do this transformation, any constant index must be a multiple of the
4764 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4765 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4766 // multiple of the variable scale.
4767 int64_t NewOffs = Offset / (int64_t)VariableScale;
4768 if (Offset != NewOffs*(int64_t)VariableScale)
4769 return 0;
4770
4771 // Okay, we can do this evaluation. Start by converting the index to intptr.
4772 const Type *IntPtrTy = TD.getIntPtrType();
4773 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004774 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00004775 true /*SExt*/,
4776 VariableIdx->getNameStart(), &I);
4777 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004778 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00004779}
4780
4781
Reid Spencere4d87aa2006-12-23 06:05:41 +00004782/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004783/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004784Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4785 ICmpInst::Predicate Cond,
4786 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004787 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004788
Chris Lattner10c0d912008-04-22 02:53:33 +00004789 // Look through bitcasts.
4790 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4791 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004792
Chris Lattner574da9b2005-01-13 20:14:25 +00004793 Value *PtrBase = GEPLHS->getOperand(0);
4794 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004795 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00004796 // This transformation (ignoring the base and scales) is valid because we
4797 // know pointers can't overflow. See if we can output an optimized form.
4798 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4799
4800 // If not, synthesize the offset the hard way.
4801 if (Offset == 0)
4802 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00004803 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4804 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004805 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004806 // If the base pointers are different, but the indices are the same, just
4807 // compare the base pointer.
4808 if (PtrBase != GEPRHS->getOperand(0)) {
4809 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004810 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004811 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004812 if (IndicesTheSame)
4813 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4814 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4815 IndicesTheSame = false;
4816 break;
4817 }
4818
4819 // If all indices are the same, just compare the base pointers.
4820 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004821 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4822 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004823
4824 // Otherwise, the base pointers are different and the indices are
4825 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004826 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004827 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004828
Chris Lattnere9d782b2005-01-13 22:25:21 +00004829 // If one of the GEPs has all zero indices, recurse.
4830 bool AllZeros = true;
4831 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4832 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4833 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4834 AllZeros = false;
4835 break;
4836 }
4837 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004838 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4839 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004840
4841 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004842 AllZeros = true;
4843 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4844 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4845 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4846 AllZeros = false;
4847 break;
4848 }
4849 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004850 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004851
Chris Lattner4401c9c2005-01-14 00:20:05 +00004852 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4853 // If the GEPs only differ by one index, compare it.
4854 unsigned NumDifferences = 0; // Keep track of # differences.
4855 unsigned DiffOperand = 0; // The operand that differs.
4856 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4857 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004858 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4859 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004860 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004861 NumDifferences = 2;
4862 break;
4863 } else {
4864 if (NumDifferences++) break;
4865 DiffOperand = i;
4866 }
4867 }
4868
4869 if (NumDifferences == 0) // SAME GEP?
4870 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004871 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00004872 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00004873
Chris Lattner4401c9c2005-01-14 00:20:05 +00004874 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004875 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4876 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004877 // Make sure we do a signed comparison here.
4878 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004879 }
4880 }
4881
Reid Spencere4d87aa2006-12-23 06:05:41 +00004882 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004883 // the result to fold to a constant!
4884 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4885 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4886 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4887 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4888 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004889 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004890 }
4891 }
4892 return 0;
4893}
4894
Chris Lattnera5406232008-05-19 20:18:56 +00004895/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4896///
4897Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4898 Instruction *LHSI,
4899 Constant *RHSC) {
4900 if (!isa<ConstantFP>(RHSC)) return 0;
4901 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4902
4903 // Get the width of the mantissa. We don't want to hack on conversions that
4904 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00004905 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00004906 if (MantissaWidth == -1) return 0; // Unknown.
4907
4908 // Check to see that the input is converted from an integer type that is small
4909 // enough that preserves all bits. TODO: check here for "known" sign bits.
4910 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4911 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4912
4913 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4914 if (isa<UIToFPInst>(LHSI))
4915 ++InputSize;
4916
4917 // If the conversion would lose info, don't hack on this.
4918 if ((int)InputSize > MantissaWidth)
4919 return 0;
4920
4921 // Otherwise, we can potentially simplify the comparison. We know that it
4922 // will always come through as an integer value and we know the constant is
4923 // not a NAN (it would have been previously simplified).
4924 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4925
4926 ICmpInst::Predicate Pred;
4927 switch (I.getPredicate()) {
4928 default: assert(0 && "Unexpected predicate!");
4929 case FCmpInst::FCMP_UEQ:
4930 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4931 case FCmpInst::FCMP_UGT:
4932 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4933 case FCmpInst::FCMP_UGE:
4934 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4935 case FCmpInst::FCMP_ULT:
4936 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4937 case FCmpInst::FCMP_ULE:
4938 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4939 case FCmpInst::FCMP_UNE:
4940 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4941 case FCmpInst::FCMP_ORD:
4942 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4943 case FCmpInst::FCMP_UNO:
4944 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4945 }
4946
4947 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4948
4949 // Now we know that the APFloat is a normal number, zero or inf.
4950
Chris Lattner85162782008-05-20 03:50:52 +00004951 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00004952 // comparing an i8 to 300.0.
4953 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4954
4955 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4956 // and large values.
4957 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4958 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4959 APFloat::rmNearestTiesToEven);
4960 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004961 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4962 Pred == ICmpInst::ICMP_SLE)
Chris Lattnera5406232008-05-19 20:18:56 +00004963 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4964 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4965 }
4966
4967 // See if the RHS value is < SignedMin.
4968 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4969 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4970 APFloat::rmNearestTiesToEven);
4971 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00004972 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4973 Pred == ICmpInst::ICMP_SGE)
Chris Lattnera5406232008-05-19 20:18:56 +00004974 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4975 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4976 }
4977
4978 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4979 // it may still be fractional. See if it is fractional by casting the FP
4980 // value to the integer value and back, checking for equality. Don't do this
4981 // for zero, because -0.0 is not fractional.
4982 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4983 if (!RHS.isZero() &&
4984 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4985 // If we had a comparison against a fractional value, we have to adjust
4986 // the compare predicate and sometimes the value. RHSC is rounded towards
4987 // zero at this point.
4988 switch (Pred) {
4989 default: assert(0 && "Unexpected integer comparison!");
4990 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
4991 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4992 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
4993 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4994 case ICmpInst::ICMP_SLE:
4995 // (float)int <= 4.4 --> int <= 4
4996 // (float)int <= -4.4 --> int < -4
4997 if (RHS.isNegative())
4998 Pred = ICmpInst::ICMP_SLT;
4999 break;
5000 case ICmpInst::ICMP_SLT:
5001 // (float)int < -4.4 --> int < -4
5002 // (float)int < 4.4 --> int <= 4
5003 if (!RHS.isNegative())
5004 Pred = ICmpInst::ICMP_SLE;
5005 break;
5006 case ICmpInst::ICMP_SGT:
5007 // (float)int > 4.4 --> int > 4
5008 // (float)int > -4.4 --> int >= -4
5009 if (RHS.isNegative())
5010 Pred = ICmpInst::ICMP_SGE;
5011 break;
5012 case ICmpInst::ICMP_SGE:
5013 // (float)int >= -4.4 --> int >= -4
5014 // (float)int >= 4.4 --> int > 4
5015 if (!RHS.isNegative())
5016 Pred = ICmpInst::ICMP_SGT;
5017 break;
5018 }
5019 }
5020
5021 // Lower this FP comparison into an appropriate integer version of the
5022 // comparison.
5023 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5024}
5025
Reid Spencere4d87aa2006-12-23 06:05:41 +00005026Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5027 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005028 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005029
Chris Lattner58e97462007-01-14 19:42:17 +00005030 // Fold trivial predicates.
5031 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5032 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5033 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5034 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5035
5036 // Simplify 'fcmp pred X, X'
5037 if (Op0 == Op1) {
5038 switch (I.getPredicate()) {
5039 default: assert(0 && "Unknown predicate!");
5040 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5041 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5042 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5043 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5044 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5045 case FCmpInst::FCMP_OLT: // True if ordered and less than
5046 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5047 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5048
5049 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5050 case FCmpInst::FCMP_ULT: // True if unordered or less than
5051 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5052 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5053 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5054 I.setPredicate(FCmpInst::FCMP_UNO);
5055 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5056 return &I;
5057
5058 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5059 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5060 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5061 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5062 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5063 I.setPredicate(FCmpInst::FCMP_ORD);
5064 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5065 return &I;
5066 }
5067 }
5068
Reid Spencere4d87aa2006-12-23 06:05:41 +00005069 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005070 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005071
Reid Spencere4d87aa2006-12-23 06:05:41 +00005072 // Handle fcmp with constant RHS
5073 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005074 // If the constant is a nan, see if we can fold the comparison based on it.
5075 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5076 if (CFP->getValueAPF().isNaN()) {
5077 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5078 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005079 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5080 "Comparison must be either ordered or unordered!");
5081 // True if unordered.
5082 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005083 }
5084 }
5085
Reid Spencere4d87aa2006-12-23 06:05:41 +00005086 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5087 switch (LHSI->getOpcode()) {
5088 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005089 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5090 // block. If in the same block, we're encouraging jump threading. If
5091 // not, we are just pessimizing the code by making an i1 phi.
5092 if (LHSI->getParent() == I.getParent())
5093 if (Instruction *NV = FoldOpIntoPhi(I))
5094 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005095 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005096 case Instruction::SIToFP:
5097 case Instruction::UIToFP:
5098 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5099 return NV;
5100 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005101 case Instruction::Select:
5102 // If either operand of the select is a constant, we can fold the
5103 // comparison into the select arms, which will cause one to be
5104 // constant folded and the select turned into a bitwise or.
5105 Value *Op1 = 0, *Op2 = 0;
5106 if (LHSI->hasOneUse()) {
5107 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5108 // Fold the known value into the constant operand.
5109 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5110 // Insert a new FCmp of the other select operand.
5111 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5112 LHSI->getOperand(2), RHSC,
5113 I.getName()), I);
5114 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5115 // Fold the known value into the constant operand.
5116 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5117 // Insert a new FCmp of the other select operand.
5118 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5119 LHSI->getOperand(1), RHSC,
5120 I.getName()), I);
5121 }
5122 }
5123
5124 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005125 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005126 break;
5127 }
5128 }
5129
5130 return Changed ? &I : 0;
5131}
5132
5133Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5134 bool Changed = SimplifyCompare(I);
5135 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5136 const Type *Ty = Op0->getType();
5137
5138 // icmp X, X
5139 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005140 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005141 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005142
5143 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005144 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005145
Reid Spencere4d87aa2006-12-23 06:05:41 +00005146 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005147 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005148 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5149 isa<ConstantPointerNull>(Op0)) &&
5150 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005151 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005152 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005153 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005154
Reid Spencere4d87aa2006-12-23 06:05:41 +00005155 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005156 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005157 switch (I.getPredicate()) {
5158 default: assert(0 && "Invalid icmp instruction!");
5159 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005160 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005161 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005162 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005163 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005164 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005165 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005166
Reid Spencere4d87aa2006-12-23 06:05:41 +00005167 case ICmpInst::ICMP_UGT:
5168 case ICmpInst::ICMP_SGT:
5169 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005170 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005171 case ICmpInst::ICMP_ULT:
5172 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005173 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005174 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005175 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005176 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005177 case ICmpInst::ICMP_UGE:
5178 case ICmpInst::ICMP_SGE:
5179 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005180 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005181 case ICmpInst::ICMP_ULE:
5182 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005183 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005184 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005185 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005186 }
5187 }
Chris Lattner8b170942002-08-09 23:47:40 +00005188 }
5189
Chris Lattner2be51ae2004-06-09 04:24:29 +00005190 // See if we are doing a comparison between a constant and an instruction that
5191 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005192 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005193 Value *A, *B;
5194
Chris Lattnerb6566012008-01-05 01:18:20 +00005195 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5196 if (I.isEquality() && CI->isNullValue() &&
5197 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5198 // (icmp cond A B) if cond is equality
5199 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005200 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005201
Reid Spencere4d87aa2006-12-23 06:05:41 +00005202 switch (I.getPredicate()) {
5203 default: break;
5204 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5205 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005206 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005207 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5208 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5209 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5210 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005211 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5212 if (CI->isMinValue(true))
5213 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5214 ConstantInt::getAllOnesValue(Op0->getType()));
5215
Reid Spencere4d87aa2006-12-23 06:05:41 +00005216 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005217
Reid Spencere4d87aa2006-12-23 06:05:41 +00005218 case ICmpInst::ICMP_SLT:
5219 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005220 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005221 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5222 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5223 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5224 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5225 break;
5226
5227 case ICmpInst::ICMP_UGT:
5228 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005229 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005230 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5231 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5232 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5233 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005234
5235 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5236 if (CI->isMaxValue(true))
5237 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5238 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005239 break;
5240
5241 case ICmpInst::ICMP_SGT:
5242 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005243 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005244 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5245 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5246 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5247 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5248 break;
5249
5250 case ICmpInst::ICMP_ULE:
5251 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005252 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005253 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5254 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5255 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5256 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5257 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005258
Reid Spencere4d87aa2006-12-23 06:05:41 +00005259 case ICmpInst::ICMP_SLE:
5260 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005261 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005262 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5263 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5264 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5265 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5266 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005267
Reid Spencere4d87aa2006-12-23 06:05:41 +00005268 case ICmpInst::ICMP_UGE:
5269 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005270 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005271 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5272 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5273 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5274 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5275 break;
5276
5277 case ICmpInst::ICMP_SGE:
5278 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005279 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005280 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5281 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5282 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5283 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5284 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005285 }
5286
Reid Spencere4d87aa2006-12-23 06:05:41 +00005287 // If we still have a icmp le or icmp ge instruction, turn it into the
5288 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005289 // already been handled above, this requires little checking.
5290 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005291 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005292 default: break;
5293 case ICmpInst::ICMP_ULE:
5294 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5295 case ICmpInst::ICMP_SLE:
5296 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5297 case ICmpInst::ICMP_UGE:
5298 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5299 case ICmpInst::ICMP_SGE:
5300 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005301 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005302
5303 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005304 // in the input. If this comparison is a normal comparison, it demands all
5305 // bits, if it is a sign bit comparison, it only demands the sign bit.
5306
5307 bool UnusedBit;
5308 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5309
Reid Spencer0460fb32007-03-22 20:36:03 +00005310 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5311 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005312 if (SimplifyDemandedBits(Op0,
5313 isSignBit ? APInt::getSignBit(BitWidth)
5314 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005315 KnownZero, KnownOne, 0))
5316 return &I;
5317
5318 // Given the known and unknown bits, compute a range that the LHS could be
5319 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005320 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005321 // Compute the Min, Max and RHS values based on the known bits. For the
5322 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005323 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5324 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005325 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005326 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5327 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005328 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005329 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5330 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005331 }
5332 switch (I.getPredicate()) { // LE/GE have been folded already.
5333 default: assert(0 && "Unknown icmp opcode!");
5334 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005335 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005336 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005337 break;
5338 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005339 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005340 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005341 break;
5342 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005343 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005344 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005345 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005346 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005347 break;
5348 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005349 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005350 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005351 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005352 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005353 break;
5354 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005355 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005356 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005357 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005358 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005359 break;
5360 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005361 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005362 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005363 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005364 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005365 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005366 }
5367 }
5368
Reid Spencere4d87aa2006-12-23 06:05:41 +00005369 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005370 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005371 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005372 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005373 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5374 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005375 }
5376
Chris Lattner01deb9d2007-04-03 17:43:25 +00005377 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005378 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5379 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5380 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005381 case Instruction::GetElementPtr:
5382 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005383 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005384 bool isAllZeros = true;
5385 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5386 if (!isa<Constant>(LHSI->getOperand(i)) ||
5387 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5388 isAllZeros = false;
5389 break;
5390 }
5391 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005392 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005393 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5394 }
5395 break;
5396
Chris Lattner6970b662005-04-23 15:31:55 +00005397 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005398 // Only fold icmp into the PHI if the phi and fcmp are in the same
5399 // block. If in the same block, we're encouraging jump threading. If
5400 // not, we are just pessimizing the code by making an i1 phi.
5401 if (LHSI->getParent() == I.getParent())
5402 if (Instruction *NV = FoldOpIntoPhi(I))
5403 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005404 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005405 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005406 // If either operand of the select is a constant, we can fold the
5407 // comparison into the select arms, which will cause one to be
5408 // constant folded and the select turned into a bitwise or.
5409 Value *Op1 = 0, *Op2 = 0;
5410 if (LHSI->hasOneUse()) {
5411 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5412 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005413 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5414 // Insert a new ICmp of the other select operand.
5415 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5416 LHSI->getOperand(2), RHSC,
5417 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005418 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5419 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005420 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5421 // Insert a new ICmp of the other select operand.
5422 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5423 LHSI->getOperand(1), RHSC,
5424 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005425 }
5426 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005427
Chris Lattner6970b662005-04-23 15:31:55 +00005428 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005429 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005430 break;
5431 }
Chris Lattner4802d902007-04-06 18:57:34 +00005432 case Instruction::Malloc:
5433 // If we have (malloc != null), and if the malloc has a single use, we
5434 // can assume it is successful and remove the malloc.
5435 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5436 AddToWorkList(LHSI);
5437 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005438 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005439 }
5440 break;
5441 }
Chris Lattner6970b662005-04-23 15:31:55 +00005442 }
5443
Reid Spencere4d87aa2006-12-23 06:05:41 +00005444 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005445 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005446 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005447 return NI;
5448 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005449 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5450 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005451 return NI;
5452
Reid Spencere4d87aa2006-12-23 06:05:41 +00005453 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005454 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5455 // now.
5456 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5457 if (isa<PointerType>(Op0->getType()) &&
5458 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005459 // We keep moving the cast from the left operand over to the right
5460 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005461 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005462
Chris Lattner57d86372007-01-06 01:45:59 +00005463 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5464 // so eliminate it as well.
5465 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5466 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005467
Chris Lattnerde90b762003-11-03 04:25:02 +00005468 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005469 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005470 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005471 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005472 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005473 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005474 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005475 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005476 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005477 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005478 }
Chris Lattner57d86372007-01-06 01:45:59 +00005479 }
5480
5481 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005482 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005483 // This comes up when you have code like
5484 // int X = A < B;
5485 // if (X) ...
5486 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005487 // with a constant or another cast from the same type.
5488 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005489 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005490 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005491 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005492
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005493 // ~x < ~y --> y < x
5494 { Value *A, *B;
5495 if (match(Op0, m_Not(m_Value(A))) &&
5496 match(Op1, m_Not(m_Value(B))))
5497 return new ICmpInst(I.getPredicate(), B, A);
5498 }
5499
Chris Lattner65b72ba2006-09-18 04:22:48 +00005500 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005501 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005502
5503 // -x == -y --> x == y
5504 if (match(Op0, m_Neg(m_Value(A))) &&
5505 match(Op1, m_Neg(m_Value(B))))
5506 return new ICmpInst(I.getPredicate(), A, B);
5507
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005508 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5509 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5510 Value *OtherVal = A == Op1 ? B : A;
5511 return new ICmpInst(I.getPredicate(), OtherVal,
5512 Constant::getNullValue(A->getType()));
5513 }
5514
5515 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5516 // A^c1 == C^c2 --> A == C^(c1^c2)
5517 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5518 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5519 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005520 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005521 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005522 return new ICmpInst(I.getPredicate(), A,
5523 InsertNewInstBefore(Xor, I));
5524 }
5525
5526 // A^B == A^D -> B == D
5527 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5528 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5529 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5530 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5531 }
5532 }
5533
5534 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5535 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005536 // A == (A^B) -> B == 0
5537 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005538 return new ICmpInst(I.getPredicate(), OtherVal,
5539 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005540 }
5541 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005542 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005543 return new ICmpInst(I.getPredicate(), B,
5544 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005545 }
5546 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005547 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005548 return new ICmpInst(I.getPredicate(), B,
5549 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005550 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005551
Chris Lattner9c2328e2006-11-14 06:06:06 +00005552 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5553 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5554 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5555 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5556 Value *X = 0, *Y = 0, *Z = 0;
5557
5558 if (A == C) {
5559 X = B; Y = D; Z = A;
5560 } else if (A == D) {
5561 X = B; Y = C; Z = A;
5562 } else if (B == C) {
5563 X = A; Y = D; Z = B;
5564 } else if (B == D) {
5565 X = A; Y = C; Z = B;
5566 }
5567
5568 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005569 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5570 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005571 I.setOperand(0, Op1);
5572 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5573 return &I;
5574 }
5575 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005576 }
Chris Lattner7e708292002-06-25 16:13:24 +00005577 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005578}
5579
Chris Lattner562ef782007-06-20 23:46:26 +00005580
5581/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5582/// and CmpRHS are both known to be integer constants.
5583Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5584 ConstantInt *DivRHS) {
5585 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5586 const APInt &CmpRHSV = CmpRHS->getValue();
5587
5588 // FIXME: If the operand types don't match the type of the divide
5589 // then don't attempt this transform. The code below doesn't have the
5590 // logic to deal with a signed divide and an unsigned compare (and
5591 // vice versa). This is because (x /s C1) <s C2 produces different
5592 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5593 // (x /u C1) <u C2. Simply casting the operands and result won't
5594 // work. :( The if statement below tests that condition and bails
5595 // if it finds it.
5596 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5597 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5598 return 0;
5599 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005600 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005601
5602 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5603 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5604 // C2 (CI). By solving for X we can turn this into a range check
5605 // instead of computing a divide.
5606 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5607
5608 // Determine if the product overflows by seeing if the product is
5609 // not equal to the divide. Make sure we do the same kind of divide
5610 // as in the LHS instruction that we're folding.
5611 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5612 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5613
5614 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005615 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005616
Chris Lattner1dbfd482007-06-21 18:11:19 +00005617 // Figure out the interval that is being checked. For example, a comparison
5618 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5619 // Compute this interval based on the constants involved and the signedness of
5620 // the compare/divide. This computes a half-open interval, keeping track of
5621 // whether either value in the interval overflows. After analysis each
5622 // overflow variable is set to 0 if it's corresponding bound variable is valid
5623 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5624 int LoOverflow = 0, HiOverflow = 0;
5625 ConstantInt *LoBound = 0, *HiBound = 0;
5626
5627
Chris Lattner562ef782007-06-20 23:46:26 +00005628 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005629 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005630 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005631 HiOverflow = LoOverflow = ProdOV;
5632 if (!HiOverflow)
5633 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005634 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005635 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005636 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005637 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5638 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005639 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005640 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5641 HiOverflow = LoOverflow = ProdOV;
5642 if (!HiOverflow)
5643 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005644 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005645 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005646 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5647 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005648 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005649 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005650 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005651 }
Dan Gohman76491272008-02-13 22:09:18 +00005652 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005653 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005654 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005655 LoBound = AddOne(DivRHS);
5656 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005657 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5658 HiOverflow = 1; // [INTMIN+1, overflow)
5659 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5660 }
Dan Gohman76491272008-02-13 22:09:18 +00005661 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005662 // e.g. X/-5 op 3 --> [-19, -14)
5663 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005664 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005665 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005666 HiBound = AddOne(Prod);
5667 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005668 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005669 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005670 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005671 HiBound = Subtract(Prod, DivRHS);
5672 }
5673
Chris Lattner1dbfd482007-06-21 18:11:19 +00005674 // Dividing by a negative swaps the condition. LT <-> GT
5675 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005676 }
5677
5678 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005679 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005680 default: assert(0 && "Unhandled icmp opcode!");
5681 case ICmpInst::ICMP_EQ:
5682 if (LoOverflow && HiOverflow)
5683 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5684 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005685 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005686 ICmpInst::ICMP_UGE, X, LoBound);
5687 else if (LoOverflow)
5688 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5689 ICmpInst::ICMP_ULT, X, HiBound);
5690 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005691 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005692 case ICmpInst::ICMP_NE:
5693 if (LoOverflow && HiOverflow)
5694 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5695 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005696 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005697 ICmpInst::ICMP_ULT, X, LoBound);
5698 else if (LoOverflow)
5699 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5700 ICmpInst::ICMP_UGE, X, HiBound);
5701 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005702 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005703 case ICmpInst::ICMP_ULT:
5704 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005705 if (LoOverflow == +1) // Low bound is greater than input range.
5706 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5707 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005708 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005709 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005710 case ICmpInst::ICMP_UGT:
5711 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005712 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005713 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005714 else if (HiOverflow == -1) // High bound less than input range.
5715 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5716 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005717 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5718 else
5719 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5720 }
5721}
5722
5723
Chris Lattner01deb9d2007-04-03 17:43:25 +00005724/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5725///
5726Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5727 Instruction *LHSI,
5728 ConstantInt *RHS) {
5729 const APInt &RHSV = RHS->getValue();
5730
5731 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005732 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005733 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5734 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5735 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005736 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5737 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005738 Value *CompareVal = LHSI->getOperand(0);
5739
5740 // If the sign bit of the XorCST is not set, there is no change to
5741 // the operation, just stop using the Xor.
5742 if (!XorCST->getValue().isNegative()) {
5743 ICI.setOperand(0, CompareVal);
5744 AddToWorkList(LHSI);
5745 return &ICI;
5746 }
5747
5748 // Was the old condition true if the operand is positive?
5749 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5750
5751 // If so, the new one isn't.
5752 isTrueIfPositive ^= true;
5753
5754 if (isTrueIfPositive)
5755 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5756 else
5757 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5758 }
5759 }
5760 break;
5761 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5762 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5763 LHSI->getOperand(0)->hasOneUse()) {
5764 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5765
5766 // If the LHS is an AND of a truncating cast, we can widen the
5767 // and/compare to be the input width without changing the value
5768 // produced, eliminating a cast.
5769 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5770 // We can do this transformation if either the AND constant does not
5771 // have its sign bit set or if it is an equality comparison.
5772 // Extending a relational comparison when we're checking the sign
5773 // bit would not work.
5774 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005775 (ICI.isEquality() ||
5776 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005777 uint32_t BitWidth =
5778 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5779 APInt NewCST = AndCST->getValue();
5780 NewCST.zext(BitWidth);
5781 APInt NewCI = RHSV;
5782 NewCI.zext(BitWidth);
5783 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005784 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00005785 ConstantInt::get(NewCST),LHSI->getName());
5786 InsertNewInstBefore(NewAnd, ICI);
5787 return new ICmpInst(ICI.getPredicate(), NewAnd,
5788 ConstantInt::get(NewCI));
5789 }
5790 }
5791
5792 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5793 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5794 // happens a LOT in code produced by the C front-end, for bitfield
5795 // access.
5796 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5797 if (Shift && !Shift->isShift())
5798 Shift = 0;
5799
5800 ConstantInt *ShAmt;
5801 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5802 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5803 const Type *AndTy = AndCST->getType(); // Type of the and.
5804
5805 // We can fold this as long as we can't shift unknown bits
5806 // into the mask. This can only happen with signed shift
5807 // rights, as they sign-extend.
5808 if (ShAmt) {
5809 bool CanFold = Shift->isLogicalShift();
5810 if (!CanFold) {
5811 // To test for the bad case of the signed shr, see if any
5812 // of the bits shifted in could be tested after the mask.
5813 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5814 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5815
5816 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5817 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5818 AndCST->getValue()) == 0)
5819 CanFold = true;
5820 }
5821
5822 if (CanFold) {
5823 Constant *NewCst;
5824 if (Shift->getOpcode() == Instruction::Shl)
5825 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5826 else
5827 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5828
5829 // Check to see if we are shifting out any of the bits being
5830 // compared.
5831 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5832 // If we shifted bits out, the fold is not going to work out.
5833 // As a special case, check to see if this means that the
5834 // result is always true or false now.
5835 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5836 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5837 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5838 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5839 } else {
5840 ICI.setOperand(1, NewCst);
5841 Constant *NewAndCST;
5842 if (Shift->getOpcode() == Instruction::Shl)
5843 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5844 else
5845 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5846 LHSI->setOperand(1, NewAndCST);
5847 LHSI->setOperand(0, Shift->getOperand(0));
5848 AddToWorkList(Shift); // Shift is dead.
5849 AddUsesToWorkList(ICI);
5850 return &ICI;
5851 }
5852 }
5853 }
5854
5855 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5856 // preferable because it allows the C<<Y expression to be hoisted out
5857 // of a loop if Y is invariant and X is not.
5858 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5859 ICI.isEquality() && !Shift->isArithmeticShift() &&
5860 isa<Instruction>(Shift->getOperand(0))) {
5861 // Compute C << Y.
5862 Value *NS;
5863 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005864 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005865 Shift->getOperand(1), "tmp");
5866 } else {
5867 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005868 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00005869 Shift->getOperand(1), "tmp");
5870 }
5871 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5872
5873 // Compute X & (C << Y).
5874 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005875 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00005876 InsertNewInstBefore(NewAnd, ICI);
5877
5878 ICI.setOperand(0, NewAnd);
5879 return &ICI;
5880 }
5881 }
5882 break;
5883
Chris Lattnera0141b92007-07-15 20:42:37 +00005884 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5885 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5886 if (!ShAmt) break;
5887
5888 uint32_t TypeBits = RHSV.getBitWidth();
5889
5890 // Check that the shift amount is in range. If not, don't perform
5891 // undefined shifts. When the shift is visited it will be
5892 // simplified.
5893 if (ShAmt->uge(TypeBits))
5894 break;
5895
5896 if (ICI.isEquality()) {
5897 // If we are comparing against bits always shifted out, the
5898 // comparison cannot succeed.
5899 Constant *Comp =
5900 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5901 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5902 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5903 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5904 return ReplaceInstUsesWith(ICI, Cst);
5905 }
5906
5907 if (LHSI->hasOneUse()) {
5908 // Otherwise strength reduce the shift into an and.
5909 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5910 Constant *Mask =
5911 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005912
Chris Lattnera0141b92007-07-15 20:42:37 +00005913 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005914 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005915 Mask, LHSI->getName()+".mask");
5916 Value *And = InsertNewInstBefore(AndI, ICI);
5917 return new ICmpInst(ICI.getPredicate(), And,
5918 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005919 }
5920 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005921
5922 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5923 bool TrueIfSigned = false;
5924 if (LHSI->hasOneUse() &&
5925 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5926 // (X << 31) <s 0 --> (X&1) != 0
5927 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5928 (TypeBits-ShAmt->getZExtValue()-1));
5929 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005930 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00005931 Mask, LHSI->getName()+".mask");
5932 Value *And = InsertNewInstBefore(AndI, ICI);
5933
5934 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5935 And, Constant::getNullValue(And->getType()));
5936 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005937 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005938 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005939
5940 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005941 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005942 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005943 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005944 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005945
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005946 // Check that the shift amount is in range. If not, don't perform
5947 // undefined shifts. When the shift is visited it will be
5948 // simplified.
5949 uint32_t TypeBits = RHSV.getBitWidth();
5950 if (ShAmt->uge(TypeBits))
5951 break;
5952
5953 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005954
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005955 // If we are comparing against bits always shifted out, the
5956 // comparison cannot succeed.
5957 APInt Comp = RHSV << ShAmtVal;
5958 if (LHSI->getOpcode() == Instruction::LShr)
5959 Comp = Comp.lshr(ShAmtVal);
5960 else
5961 Comp = Comp.ashr(ShAmtVal);
5962
5963 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5964 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5965 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5966 return ReplaceInstUsesWith(ICI, Cst);
5967 }
5968
5969 // Otherwise, check to see if the bits shifted out are known to be zero.
5970 // If so, we can compare against the unshifted value:
5971 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00005972 if (LHSI->hasOneUse() &&
5973 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005974 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5975 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5976 ConstantExpr::getShl(RHS, ShAmt));
5977 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005978
Evan Chengf30752c2008-04-23 00:38:06 +00005979 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005980 // Otherwise strength reduce the shift into an and.
5981 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5982 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00005983
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005984 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005985 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005986 Mask, LHSI->getName()+".mask");
5987 Value *And = InsertNewInstBefore(AndI, ICI);
5988 return new ICmpInst(ICI.getPredicate(), And,
5989 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005990 }
5991 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005992 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005993
5994 case Instruction::SDiv:
5995 case Instruction::UDiv:
5996 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5997 // Fold this div into the comparison, producing a range check.
5998 // Determine, based on the divide type, what the range is being
5999 // checked. If there is an overflow on the low or high side, remember
6000 // it, otherwise compute the range [low, hi) bounding the new value.
6001 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006002 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6003 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6004 DivRHS))
6005 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006006 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006007
6008 case Instruction::Add:
6009 // Fold: icmp pred (add, X, C1), C2
6010
6011 if (!ICI.isEquality()) {
6012 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6013 if (!LHSC) break;
6014 const APInt &LHSV = LHSC->getValue();
6015
6016 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6017 .subtract(LHSV);
6018
6019 if (ICI.isSignedPredicate()) {
6020 if (CR.getLower().isSignBit()) {
6021 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6022 ConstantInt::get(CR.getUpper()));
6023 } else if (CR.getUpper().isSignBit()) {
6024 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6025 ConstantInt::get(CR.getLower()));
6026 }
6027 } else {
6028 if (CR.getLower().isMinValue()) {
6029 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6030 ConstantInt::get(CR.getUpper()));
6031 } else if (CR.getUpper().isMinValue()) {
6032 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6033 ConstantInt::get(CR.getLower()));
6034 }
6035 }
6036 }
6037 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006038 }
6039
6040 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6041 if (ICI.isEquality()) {
6042 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6043
6044 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6045 // the second operand is a constant, simplify a bit.
6046 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6047 switch (BO->getOpcode()) {
6048 case Instruction::SRem:
6049 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6050 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6051 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6052 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6053 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006054 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006055 BO->getName());
6056 InsertNewInstBefore(NewRem, ICI);
6057 return new ICmpInst(ICI.getPredicate(), NewRem,
6058 Constant::getNullValue(BO->getType()));
6059 }
6060 }
6061 break;
6062 case Instruction::Add:
6063 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6064 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6065 if (BO->hasOneUse())
6066 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6067 Subtract(RHS, BOp1C));
6068 } else if (RHSV == 0) {
6069 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6070 // efficiently invertible, or if the add has just this one use.
6071 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6072
6073 if (Value *NegVal = dyn_castNegVal(BOp1))
6074 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6075 else if (Value *NegVal = dyn_castNegVal(BOp0))
6076 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6077 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006078 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006079 InsertNewInstBefore(Neg, ICI);
6080 Neg->takeName(BO);
6081 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6082 }
6083 }
6084 break;
6085 case Instruction::Xor:
6086 // For the xor case, we can xor two constants together, eliminating
6087 // the explicit xor.
6088 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6089 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6090 ConstantExpr::getXor(RHS, BOC));
6091
6092 // FALLTHROUGH
6093 case Instruction::Sub:
6094 // Replace (([sub|xor] A, B) != 0) with (A != B)
6095 if (RHSV == 0)
6096 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6097 BO->getOperand(1));
6098 break;
6099
6100 case Instruction::Or:
6101 // If bits are being or'd in that are not present in the constant we
6102 // are comparing against, then the comparison could never succeed!
6103 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6104 Constant *NotCI = ConstantExpr::getNot(RHS);
6105 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6106 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6107 isICMP_NE));
6108 }
6109 break;
6110
6111 case Instruction::And:
6112 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6113 // If bits are being compared against that are and'd out, then the
6114 // comparison can never succeed!
6115 if ((RHSV & ~BOC->getValue()) != 0)
6116 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6117 isICMP_NE));
6118
6119 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6120 if (RHS == BOC && RHSV.isPowerOf2())
6121 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6122 ICmpInst::ICMP_NE, LHSI,
6123 Constant::getNullValue(RHS->getType()));
6124
6125 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006126 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006127 Value *X = BO->getOperand(0);
6128 Constant *Zero = Constant::getNullValue(X->getType());
6129 ICmpInst::Predicate pred = isICMP_NE ?
6130 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6131 return new ICmpInst(pred, X, Zero);
6132 }
6133
6134 // ((X & ~7) == 0) --> X < 8
6135 if (RHSV == 0 && isHighOnes(BOC)) {
6136 Value *X = BO->getOperand(0);
6137 Constant *NegX = ConstantExpr::getNeg(BOC);
6138 ICmpInst::Predicate pred = isICMP_NE ?
6139 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6140 return new ICmpInst(pred, X, NegX);
6141 }
6142 }
6143 default: break;
6144 }
6145 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6146 // Handle icmp {eq|ne} <intrinsic>, intcst.
6147 if (II->getIntrinsicID() == Intrinsic::bswap) {
6148 AddToWorkList(II);
6149 ICI.setOperand(0, II->getOperand(1));
6150 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6151 return &ICI;
6152 }
6153 }
6154 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006155 // If the LHS is a cast from an integral value of the same size,
6156 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006157 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6158 Value *CastOp = Cast->getOperand(0);
6159 const Type *SrcTy = CastOp->getType();
6160 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6161 if (SrcTy->isInteger() &&
6162 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6163 // If this is an unsigned comparison, try to make the comparison use
6164 // smaller constant values.
6165 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6166 // X u< 128 => X s> -1
6167 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6168 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6169 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6170 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6171 // X u> 127 => X s< 0
6172 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6173 Constant::getNullValue(SrcTy));
6174 }
6175 }
6176 }
6177 }
6178 return 0;
6179}
6180
6181/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6182/// We only handle extending casts so far.
6183///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006184Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6185 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006186 Value *LHSCIOp = LHSCI->getOperand(0);
6187 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006188 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006189 Value *RHSCIOp;
6190
Chris Lattner8c756c12007-05-05 22:41:33 +00006191 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6192 // integer type is the same size as the pointer type.
6193 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6194 getTargetData().getPointerSizeInBits() ==
6195 cast<IntegerType>(DestTy)->getBitWidth()) {
6196 Value *RHSOp = 0;
6197 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006198 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006199 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6200 RHSOp = RHSC->getOperand(0);
6201 // If the pointer types don't match, insert a bitcast.
6202 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006203 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006204 }
6205
6206 if (RHSOp)
6207 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6208 }
6209
6210 // The code below only handles extension cast instructions, so far.
6211 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006212 if (LHSCI->getOpcode() != Instruction::ZExt &&
6213 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006214 return 0;
6215
Reid Spencere4d87aa2006-12-23 06:05:41 +00006216 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6217 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006218
Reid Spencere4d87aa2006-12-23 06:05:41 +00006219 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006220 // Not an extension from the same type?
6221 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006222 if (RHSCIOp->getType() != LHSCIOp->getType())
6223 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006224
Nick Lewycky4189a532008-01-28 03:48:02 +00006225 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006226 // and the other is a zext), then we can't handle this.
6227 if (CI->getOpcode() != LHSCI->getOpcode())
6228 return 0;
6229
Nick Lewycky4189a532008-01-28 03:48:02 +00006230 // Deal with equality cases early.
6231 if (ICI.isEquality())
6232 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6233
6234 // A signed comparison of sign extended values simplifies into a
6235 // signed comparison.
6236 if (isSignedCmp && isSignedExt)
6237 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6238
6239 // The other three cases all fold into an unsigned comparison.
6240 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006241 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006242
Reid Spencere4d87aa2006-12-23 06:05:41 +00006243 // If we aren't dealing with a constant on the RHS, exit early
6244 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6245 if (!CI)
6246 return 0;
6247
6248 // Compute the constant that would happen if we truncated to SrcTy then
6249 // reextended to DestTy.
6250 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6251 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6252
6253 // If the re-extended constant didn't change...
6254 if (Res2 == CI) {
6255 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6256 // For example, we might have:
6257 // %A = sext short %X to uint
6258 // %B = icmp ugt uint %A, 1330
6259 // It is incorrect to transform this into
6260 // %B = icmp ugt short %X, 1330
6261 // because %A may have negative value.
6262 //
6263 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6264 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006265 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006266 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6267 else
6268 return 0;
6269 }
6270
6271 // The re-extended constant changed so the constant cannot be represented
6272 // in the shorter type. Consequently, we cannot emit a simple comparison.
6273
6274 // First, handle some easy cases. We know the result cannot be equal at this
6275 // point so handle the ICI.isEquality() cases
6276 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006277 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006278 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006279 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006280
6281 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6282 // should have been folded away previously and not enter in here.
6283 Value *Result;
6284 if (isSignedCmp) {
6285 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006286 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006287 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006288 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006289 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006290 } else {
6291 // We're performing an unsigned comparison.
6292 if (isSignedExt) {
6293 // We're performing an unsigned comp with a sign extended value.
6294 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006295 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006296 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6297 NegOne, ICI.getName()), ICI);
6298 } else {
6299 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006300 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006301 }
6302 }
6303
6304 // Finally, return the value computed.
6305 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6306 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6307 return ReplaceInstUsesWith(ICI, Result);
6308 } else {
6309 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6310 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6311 "ICmp should be folded!");
6312 if (Constant *CI = dyn_cast<Constant>(Result))
6313 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6314 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006315 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006316 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006317}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006318
Reid Spencer832254e2007-02-02 02:16:23 +00006319Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6320 return commonShiftTransforms(I);
6321}
6322
6323Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6324 return commonShiftTransforms(I);
6325}
6326
6327Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006328 if (Instruction *R = commonShiftTransforms(I))
6329 return R;
6330
6331 Value *Op0 = I.getOperand(0);
6332
6333 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6334 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6335 if (CSI->isAllOnesValue())
6336 return ReplaceInstUsesWith(I, CSI);
6337
6338 // See if we can turn a signed shr into an unsigned shr.
6339 if (MaskedValueIsZero(Op0,
6340 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006341 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006342
6343 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006344}
6345
6346Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6347 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006348 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006349
6350 // shl X, 0 == X and shr X, 0 == X
6351 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006352 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006353 Op0 == Constant::getNullValue(Op0->getType()))
6354 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006355
Reid Spencere4d87aa2006-12-23 06:05:41 +00006356 if (isa<UndefValue>(Op0)) {
6357 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006358 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006359 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006360 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6361 }
6362 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006363 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6364 return ReplaceInstUsesWith(I, Op0);
6365 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006366 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006367 }
6368
Chris Lattner2eefe512004-04-09 19:05:30 +00006369 // Try to fold constant and into select arguments.
6370 if (isa<Constant>(Op0))
6371 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006372 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006373 return R;
6374
Reid Spencerb83eb642006-10-20 07:07:24 +00006375 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006376 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6377 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006378 return 0;
6379}
6380
Reid Spencerb83eb642006-10-20 07:07:24 +00006381Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006382 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006383 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006384
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006385 // See if we can simplify any instructions used by the instruction whose sole
6386 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006387 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6388 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6389 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006390 KnownZero, KnownOne))
6391 return &I;
6392
Chris Lattner4d5542c2006-01-06 07:12:35 +00006393 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6394 // of a signed value.
6395 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006396 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006397 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006398 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6399 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006400 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006401 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006402 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006403 }
6404
6405 // ((X*C1) << C2) == (X * (C1 << C2))
6406 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6407 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6408 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006409 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006410 ConstantExpr::getShl(BOOp, Op1));
6411
6412 // Try to fold constant and into select arguments.
6413 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6414 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6415 return R;
6416 if (isa<PHINode>(Op0))
6417 if (Instruction *NV = FoldOpIntoPhi(I))
6418 return NV;
6419
Chris Lattner8999dd32007-12-22 09:07:47 +00006420 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6421 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6422 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6423 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6424 // place. Don't try to do this transformation in this case. Also, we
6425 // require that the input operand is a shift-by-constant so that we have
6426 // confidence that the shifts will get folded together. We could do this
6427 // xform in more cases, but it is unlikely to be profitable.
6428 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6429 isa<ConstantInt>(TrOp->getOperand(1))) {
6430 // Okay, we'll do this xform. Make the shift of shift.
6431 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006432 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006433 I.getName());
6434 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6435
6436 // For logical shifts, the truncation has the effect of making the high
6437 // part of the register be zeros. Emulate this by inserting an AND to
6438 // clear the top bits as needed. This 'and' will usually be zapped by
6439 // other xforms later if dead.
6440 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6441 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6442 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6443
6444 // The mask we constructed says what the trunc would do if occurring
6445 // between the shifts. We want to know the effect *after* the second
6446 // shift. We know that it is a logical shift by a constant, so adjust the
6447 // mask as appropriate.
6448 if (I.getOpcode() == Instruction::Shl)
6449 MaskV <<= Op1->getZExtValue();
6450 else {
6451 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6452 MaskV = MaskV.lshr(Op1->getZExtValue());
6453 }
6454
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006455 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006456 TI->getName());
6457 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6458
6459 // Return the value truncated to the interesting size.
6460 return new TruncInst(And, I.getType());
6461 }
6462 }
6463
Chris Lattner4d5542c2006-01-06 07:12:35 +00006464 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006465 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6466 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6467 Value *V1, *V2;
6468 ConstantInt *CC;
6469 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006470 default: break;
6471 case Instruction::Add:
6472 case Instruction::And:
6473 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006474 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006475 // These operators commute.
6476 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006477 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6478 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006479 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006480 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006481 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006482 Op0BO->getName());
6483 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006484 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006485 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006486 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006487 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006488 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006489 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006490 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006491 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006492
Chris Lattner150f12a2005-09-18 06:30:59 +00006493 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006494 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006495 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006496 match(Op0BOOp1,
6497 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006498 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6499 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006500 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006501 Op0BO->getOperand(0), Op1,
6502 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006503 InsertNewInstBefore(YS, I); // (Y << C)
6504 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006505 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006506 V1->getName()+".mask");
6507 InsertNewInstBefore(XM, I); // X & (CC << C)
6508
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006509 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006510 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006511 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006512
Reid Spencera07cb7d2007-02-02 14:41:37 +00006513 // FALL THROUGH.
6514 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006515 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006516 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6517 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006518 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006519 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006520 Op0BO->getOperand(1), Op1,
6521 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006522 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006523 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006524 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006525 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006526 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006527 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006528 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006529 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006530 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006531
Chris Lattner13d4ab42006-05-31 21:14:00 +00006532 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006533 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6534 match(Op0BO->getOperand(0),
6535 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006536 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006537 cast<BinaryOperator>(Op0BO->getOperand(0))
6538 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006539 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006540 Op0BO->getOperand(1), Op1,
6541 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006542 InsertNewInstBefore(YS, I); // (Y << C)
6543 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006544 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006545 V1->getName()+".mask");
6546 InsertNewInstBefore(XM, I); // X & (CC << C)
6547
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006548 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006549 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006550
Chris Lattner11021cb2005-09-18 05:12:10 +00006551 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006552 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006553 }
6554
6555
6556 // If the operand is an bitwise operator with a constant RHS, and the
6557 // shift is the only use, we can pull it out of the shift.
6558 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6559 bool isValid = true; // Valid only for And, Or, Xor
6560 bool highBitSet = false; // Transform if high bit of constant set?
6561
6562 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006563 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006564 case Instruction::Add:
6565 isValid = isLeftShift;
6566 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006567 case Instruction::Or:
6568 case Instruction::Xor:
6569 highBitSet = false;
6570 break;
6571 case Instruction::And:
6572 highBitSet = true;
6573 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006574 }
6575
6576 // If this is a signed shift right, and the high bit is modified
6577 // by the logical operation, do not perform the transformation.
6578 // The highBitSet boolean indicates the value of the high bit of
6579 // the constant which would cause it to be modified for this
6580 // operation.
6581 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006582 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006583 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006584
6585 if (isValid) {
6586 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6587
6588 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006589 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006590 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006591 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006592
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006593 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006594 NewRHS);
6595 }
6596 }
6597 }
6598 }
6599
Chris Lattnerad0124c2006-01-06 07:52:12 +00006600 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006601 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6602 if (ShiftOp && !ShiftOp->isShift())
6603 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006604
Reid Spencerb83eb642006-10-20 07:07:24 +00006605 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006606 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006607 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6608 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006609 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6610 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6611 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006612
Zhou Sheng4351c642007-04-02 08:20:41 +00006613 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006614 if (AmtSum > TypeBits)
6615 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006616
6617 const IntegerType *Ty = cast<IntegerType>(I.getType());
6618
6619 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006620 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006621 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006622 ConstantInt::get(Ty, AmtSum));
6623 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6624 I.getOpcode() == Instruction::AShr) {
6625 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006626 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006627 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6628 I.getOpcode() == Instruction::LShr) {
6629 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6630 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006631 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006632 InsertNewInstBefore(Shift, I);
6633
Zhou Shenge9e03f62007-03-28 15:02:20 +00006634 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006635 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006636 }
6637
Chris Lattnerb87056f2007-02-05 00:57:54 +00006638 // Okay, if we get here, one shift must be left, and the other shift must be
6639 // right. See if the amounts are equal.
6640 if (ShiftAmt1 == ShiftAmt2) {
6641 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6642 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006643 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006644 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006645 }
6646 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6647 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006648 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006649 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006650 }
6651 // We can simplify ((X << C) >>s C) into a trunc + sext.
6652 // NOTE: we could do this for any C, but that would make 'unusual' integer
6653 // types. For now, just stick to ones well-supported by the code
6654 // generators.
6655 const Type *SExtType = 0;
6656 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006657 case 1 :
6658 case 8 :
6659 case 16 :
6660 case 32 :
6661 case 64 :
6662 case 128:
6663 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6664 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006665 default: break;
6666 }
6667 if (SExtType) {
6668 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6669 InsertNewInstBefore(NewTrunc, I);
6670 return new SExtInst(NewTrunc, Ty);
6671 }
6672 // Otherwise, we can't handle it yet.
6673 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006674 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006675
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006676 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006677 if (I.getOpcode() == Instruction::Shl) {
6678 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6679 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006680 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006681 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006682 InsertNewInstBefore(Shift, I);
6683
Reid Spencer55702aa2007-03-25 21:11:44 +00006684 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006685 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006686 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006687
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006688 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006689 if (I.getOpcode() == Instruction::LShr) {
6690 assert(ShiftOp->getOpcode() == Instruction::Shl);
6691 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006692 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006693 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006694
Reid Spencerd5e30f02007-03-26 17:18:58 +00006695 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006696 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006697 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006698
6699 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6700 } else {
6701 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006702 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006703
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006704 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006705 if (I.getOpcode() == Instruction::Shl) {
6706 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6707 ShiftOp->getOpcode() == Instruction::AShr);
6708 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006709 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006710 ConstantInt::get(Ty, ShiftDiff));
6711 InsertNewInstBefore(Shift, I);
6712
Reid Spencer55702aa2007-03-25 21:11:44 +00006713 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006714 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006715 }
6716
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006717 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006718 if (I.getOpcode() == Instruction::LShr) {
6719 assert(ShiftOp->getOpcode() == Instruction::Shl);
6720 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006721 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006722 InsertNewInstBefore(Shift, I);
6723
Reid Spencer68d27cf2007-03-26 23:45:51 +00006724 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006725 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006726 }
6727
6728 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006729 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006730 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006731 return 0;
6732}
6733
Chris Lattnera1be5662002-05-02 17:06:02 +00006734
Chris Lattnercfd65102005-10-29 04:36:15 +00006735/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6736/// expression. If so, decompose it, returning some value X, such that Val is
6737/// X*Scale+Offset.
6738///
6739static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006740 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006741 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006742 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006743 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006744 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006745 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006746 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6747 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6748 if (I->getOpcode() == Instruction::Shl) {
6749 // This is a value scaled by '1 << the shift amt'.
6750 Scale = 1U << RHS->getZExtValue();
6751 Offset = 0;
6752 return I->getOperand(0);
6753 } else if (I->getOpcode() == Instruction::Mul) {
6754 // This value is scaled by 'RHS'.
6755 Scale = RHS->getZExtValue();
6756 Offset = 0;
6757 return I->getOperand(0);
6758 } else if (I->getOpcode() == Instruction::Add) {
6759 // We have X+C. Check to see if we really have (X*C2)+C1,
6760 // where C1 is divisible by C2.
6761 unsigned SubScale;
6762 Value *SubVal =
6763 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6764 Offset += RHS->getZExtValue();
6765 Scale = SubScale;
6766 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006767 }
6768 }
6769 }
6770
6771 // Otherwise, we can't look past this.
6772 Scale = 1;
6773 Offset = 0;
6774 return Val;
6775}
6776
6777
Chris Lattnerb3f83972005-10-24 06:03:58 +00006778/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6779/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006780Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006781 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006782 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006783
Chris Lattnerb53c2382005-10-24 06:22:12 +00006784 // Remove any uses of AI that are dead.
6785 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006786
Chris Lattnerb53c2382005-10-24 06:22:12 +00006787 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6788 Instruction *User = cast<Instruction>(*UI++);
6789 if (isInstructionTriviallyDead(User)) {
6790 while (UI != E && *UI == User)
6791 ++UI; // If this instruction uses AI more than once, don't break UI.
6792
Chris Lattnerb53c2382005-10-24 06:22:12 +00006793 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006794 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006795 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006796 }
6797 }
6798
Chris Lattnerb3f83972005-10-24 06:03:58 +00006799 // Get the type really allocated and the type casted to.
6800 const Type *AllocElTy = AI.getAllocatedType();
6801 const Type *CastElTy = PTy->getElementType();
6802 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006803
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006804 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6805 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006806 if (CastElTyAlign < AllocElTyAlign) return 0;
6807
Chris Lattner39387a52005-10-24 06:35:18 +00006808 // If the allocation has multiple uses, only promote it if we are strictly
6809 // increasing the alignment of the resultant allocation. If we keep it the
6810 // same, we open the door to infinite loops of various kinds.
6811 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6812
Duncan Sands514ab342007-11-01 20:53:16 +00006813 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6814 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006815 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006816
Chris Lattner455fcc82005-10-29 03:19:53 +00006817 // See if we can satisfy the modulus by pulling a scale out of the array
6818 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006819 unsigned ArraySizeScale;
6820 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006821 Value *NumElements = // See if the array size is a decomposable linear expr.
6822 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6823
Chris Lattner455fcc82005-10-29 03:19:53 +00006824 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6825 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006826 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6827 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006828
Chris Lattner455fcc82005-10-29 03:19:53 +00006829 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6830 Value *Amt = 0;
6831 if (Scale == 1) {
6832 Amt = NumElements;
6833 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006834 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006835 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6836 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006837 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006838 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006839 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006840 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00006841 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006842 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006843 }
6844
Jeff Cohen86796be2007-04-04 16:58:57 +00006845 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6846 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006847 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00006848 Amt = InsertNewInstBefore(Tmp, AI);
6849 }
6850
Chris Lattnerb3f83972005-10-24 06:03:58 +00006851 AllocationInst *New;
6852 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006853 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006854 else
Chris Lattner6934a042007-02-11 01:23:03 +00006855 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006856 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006857 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006858
6859 // If the allocation has multiple uses, insert a cast and change all things
6860 // that used it to use the new cast. This will also hack on CI, but it will
6861 // die soon.
6862 if (!AI.hasOneUse()) {
6863 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006864 // New is the allocation instruction, pointer typed. AI is the original
6865 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6866 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006867 InsertNewInstBefore(NewCast, AI);
6868 AI.replaceAllUsesWith(NewCast);
6869 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006870 return ReplaceInstUsesWith(CI, New);
6871}
6872
Chris Lattner70074e02006-05-13 02:06:03 +00006873/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006874/// and return it as type Ty without inserting any new casts and without
6875/// changing the computed value. This is used by code that tries to decide
6876/// whether promoting or shrinking integer operations to wider or smaller types
6877/// will allow us to eliminate a truncate or extend.
6878///
6879/// This is a truncation operation if Ty is smaller than V->getType(), or an
6880/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00006881///
6882/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
6883/// should return true if trunc(V) can be computed by computing V in the smaller
6884/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
6885/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6886/// efficiently truncated.
6887///
6888/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6889/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6890/// the final result.
Dan Gohmaneee962e2008-04-10 18:43:06 +00006891bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6892 unsigned CastOpc,
6893 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006894 // We can always evaluate constants in another type.
6895 if (isa<ConstantInt>(V))
6896 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006897
6898 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006899 if (!I) return false;
6900
6901 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006902
Chris Lattner951626b2007-08-02 06:11:14 +00006903 // If this is an extension or truncate, we can often eliminate it.
6904 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6905 // If this is a cast from the destination type, we can trivially eliminate
6906 // it, and this will remove a cast overall.
6907 if (I->getOperand(0)->getType() == Ty) {
6908 // If the first operand is itself a cast, and is eliminable, do not count
6909 // this as an eliminable cast. We would prefer to eliminate those two
6910 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00006911 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00006912 ++NumCastsRemoved;
6913 return true;
6914 }
6915 }
6916
6917 // We can't extend or shrink something that has multiple uses: doing so would
6918 // require duplicating the instruction in general, which isn't profitable.
6919 if (!I->hasOneUse()) return false;
6920
Chris Lattner70074e02006-05-13 02:06:03 +00006921 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006922 case Instruction::Add:
6923 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006924 case Instruction::And:
6925 case Instruction::Or:
6926 case Instruction::Xor:
6927 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006928 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6929 NumCastsRemoved) &&
6930 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6931 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006932
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006933 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006934 // A multiply can be truncated by truncating its operands.
6935 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6936 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6937 NumCastsRemoved) &&
6938 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6939 NumCastsRemoved);
6940
Chris Lattner46b96052006-11-29 07:18:39 +00006941 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006942 // If we are truncating the result of this SHL, and if it's a shift of a
6943 // constant amount, we can always perform a SHL in a smaller type.
6944 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006945 uint32_t BitWidth = Ty->getBitWidth();
6946 if (BitWidth < OrigTy->getBitWidth() &&
6947 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006948 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6949 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006950 }
6951 break;
6952 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006953 // If this is a truncate of a logical shr, we can truncate it to a smaller
6954 // lshr iff we know that the bits we would otherwise be shifting in are
6955 // already zeros.
6956 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006957 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6958 uint32_t BitWidth = Ty->getBitWidth();
6959 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006960 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006961 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6962 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006963 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6964 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006965 }
6966 }
Chris Lattner46b96052006-11-29 07:18:39 +00006967 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006968 case Instruction::ZExt:
6969 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006970 case Instruction::Trunc:
6971 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006972 // can safely replace it. Note that replacing it does not reduce the number
6973 // of casts in the input.
6974 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006975 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00006976 break;
Chris Lattner8114b712008-06-18 04:00:49 +00006977
6978 case Instruction::PHI: {
6979 // We can change a phi if we can change all operands.
6980 PHINode *PN = cast<PHINode>(I);
6981 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
6982 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
6983 NumCastsRemoved))
6984 return false;
6985 return true;
6986 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006987 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006988 // TODO: Can handle more cases here.
6989 break;
6990 }
6991
6992 return false;
6993}
6994
6995/// EvaluateInDifferentType - Given an expression that
6996/// CanEvaluateInDifferentType returns true for, actually insert the code to
6997/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006998Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006999 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007000 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007001 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007002
7003 // Otherwise, it must be an instruction.
7004 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007005 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007006 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007007 case Instruction::Add:
7008 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007009 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007010 case Instruction::And:
7011 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007012 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007013 case Instruction::AShr:
7014 case Instruction::LShr:
7015 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007016 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007017 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007018 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattner8114b712008-06-18 04:00:49 +00007019 LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007020 break;
7021 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007022 case Instruction::Trunc:
7023 case Instruction::ZExt:
7024 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007025 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007026 // just return the source. There's no need to insert it because it is not
7027 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007028 if (I->getOperand(0)->getType() == Ty)
7029 return I->getOperand(0);
7030
Chris Lattner8114b712008-06-18 04:00:49 +00007031 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007032 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007033 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007034 break;
Chris Lattner8114b712008-06-18 04:00:49 +00007035 case Instruction::PHI: {
7036 PHINode *OPN = cast<PHINode>(I);
7037 PHINode *NPN = PHINode::Create(Ty);
7038 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7039 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7040 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7041 }
7042 Res = NPN;
7043 break;
7044 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007045 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007046 // TODO: Can handle more cases here.
7047 assert(0 && "Unreachable!");
7048 break;
7049 }
7050
Chris Lattner8114b712008-06-18 04:00:49 +00007051 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007052 return InsertNewInstBefore(Res, *I);
7053}
7054
Reid Spencer3da59db2006-11-27 01:05:10 +00007055/// @brief Implement the transforms common to all CastInst visitors.
7056Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007057 Value *Src = CI.getOperand(0);
7058
Dan Gohman23d9d272007-05-11 21:10:54 +00007059 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007060 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007061 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007062 if (Instruction::CastOps opc =
7063 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7064 // The first cast (CSrc) is eliminable so we need to fix up or replace
7065 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007066 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007067 }
7068 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007069
Reid Spencer3da59db2006-11-27 01:05:10 +00007070 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007071 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7072 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7073 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007074
7075 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007076 if (isa<PHINode>(Src))
7077 if (Instruction *NV = FoldOpIntoPhi(CI))
7078 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007079
Reid Spencer3da59db2006-11-27 01:05:10 +00007080 return 0;
7081}
7082
Chris Lattnerd3e28342007-04-27 17:44:50 +00007083/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7084Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7085 Value *Src = CI.getOperand(0);
7086
Chris Lattnerd3e28342007-04-27 17:44:50 +00007087 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007088 // If casting the result of a getelementptr instruction with no offset, turn
7089 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007090 if (GEP->hasAllZeroIndices()) {
7091 // Changing the cast operand is usually not a good idea but it is safe
7092 // here because the pointer operand is being replaced with another
7093 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007094 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007095 CI.setOperand(0, GEP->getOperand(0));
7096 return &CI;
7097 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007098
7099 // If the GEP has a single use, and the base pointer is a bitcast, and the
7100 // GEP computes a constant offset, see if we can convert these three
7101 // instructions into fewer. This typically happens with unions and other
7102 // non-type-safe code.
7103 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7104 if (GEP->hasAllConstantIndices()) {
7105 // We are guaranteed to get a constant from EmitGEPOffset.
7106 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7107 int64_t Offset = OffsetV->getSExtValue();
7108
7109 // Get the base pointer input of the bitcast, and the type it points to.
7110 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7111 const Type *GEPIdxTy =
7112 cast<PointerType>(OrigBase->getType())->getElementType();
7113 if (GEPIdxTy->isSized()) {
7114 SmallVector<Value*, 8> NewIndices;
7115
Chris Lattnerc42e2262007-05-05 01:59:31 +00007116 // Start with the index over the outer type. Note that the type size
7117 // might be zero (even if the offset isn't zero) if the indexed type
7118 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007119 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007120 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007121 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007122 FirstIdx = Offset/TySize;
7123 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007124
Chris Lattnerc42e2262007-05-05 01:59:31 +00007125 // Handle silly modulus not returning values values [0..TySize).
7126 if (Offset < 0) {
7127 --FirstIdx;
7128 Offset += TySize;
7129 assert(Offset >= 0);
7130 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007131 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007132 }
7133
7134 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007135
7136 // Index into the types. If we fail, set OrigBase to null.
7137 while (Offset) {
7138 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7139 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007140 if (Offset < (int64_t)SL->getSizeInBytes()) {
7141 unsigned Elt = SL->getElementContainingOffset(Offset);
7142 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007143
Chris Lattner6b6aef82007-05-15 00:16:00 +00007144 Offset -= SL->getElementOffset(Elt);
7145 GEPIdxTy = STy->getElementType(Elt);
7146 } else {
7147 // Otherwise, we can't index into this, bail out.
7148 Offset = 0;
7149 OrigBase = 0;
7150 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007151 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7152 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007153 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007154 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7155 Offset %= EltSize;
7156 } else {
7157 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7158 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007159 GEPIdxTy = STy->getElementType();
7160 } else {
7161 // Otherwise, we can't index into this, bail out.
7162 Offset = 0;
7163 OrigBase = 0;
7164 }
7165 }
7166 if (OrigBase) {
7167 // If we were able to index down into an element, create the GEP
7168 // and bitcast the result. This eliminates one bitcast, potentially
7169 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007170 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7171 NewIndices.begin(),
7172 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007173 InsertNewInstBefore(NGEP, CI);
7174 NGEP->takeName(GEP);
7175
Chris Lattner9bc14642007-04-28 00:57:34 +00007176 if (isa<BitCastInst>(CI))
7177 return new BitCastInst(NGEP, CI.getType());
7178 assert(isa<PtrToIntInst>(CI));
7179 return new PtrToIntInst(NGEP, CI.getType());
7180 }
7181 }
7182 }
7183 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007184 }
7185
7186 return commonCastTransforms(CI);
7187}
7188
7189
7190
Chris Lattnerc739cd62007-03-03 05:27:34 +00007191/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7192/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007193/// cases.
7194/// @brief Implement the transforms common to CastInst with integer operands
7195Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7196 if (Instruction *Result = commonCastTransforms(CI))
7197 return Result;
7198
7199 Value *Src = CI.getOperand(0);
7200 const Type *SrcTy = Src->getType();
7201 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007202 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7203 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007204
Reid Spencer3da59db2006-11-27 01:05:10 +00007205 // See if we can simplify any instructions used by the LHS whose sole
7206 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007207 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7208 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007209 KnownZero, KnownOne))
7210 return &CI;
7211
7212 // If the source isn't an instruction or has more than one use then we
7213 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007214 Instruction *SrcI = dyn_cast<Instruction>(Src);
7215 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007216 return 0;
7217
Chris Lattnerc739cd62007-03-03 05:27:34 +00007218 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007219 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007220 if (!isa<BitCastInst>(CI) &&
7221 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007222 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007223 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007224 // eliminates the cast, so it is always a win. If this is a zero-extension,
7225 // we need to do an AND to maintain the clear top-part of the computation,
7226 // so we require that the input have eliminated at least one cast. If this
7227 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007228 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007229 bool DoXForm;
7230 switch (CI.getOpcode()) {
7231 default:
7232 // All the others use floating point so we shouldn't actually
7233 // get here because of the check above.
7234 assert(0 && "Unknown cast type");
7235 case Instruction::Trunc:
7236 DoXForm = true;
7237 break;
7238 case Instruction::ZExt:
7239 DoXForm = NumCastsRemoved >= 1;
7240 break;
7241 case Instruction::SExt:
7242 DoXForm = NumCastsRemoved >= 2;
7243 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007244 }
7245
7246 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007247 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7248 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007249 assert(Res->getType() == DestTy);
7250 switch (CI.getOpcode()) {
7251 default: assert(0 && "Unknown cast type!");
7252 case Instruction::Trunc:
7253 case Instruction::BitCast:
7254 // Just replace this cast with the result.
7255 return ReplaceInstUsesWith(CI, Res);
7256 case Instruction::ZExt: {
7257 // We need to emit an AND to clear the high bits.
7258 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007259 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7260 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007261 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007262 }
7263 case Instruction::SExt:
7264 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007265 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007266 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7267 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007268 }
7269 }
7270 }
7271
7272 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7273 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7274
7275 switch (SrcI->getOpcode()) {
7276 case Instruction::Add:
7277 case Instruction::Mul:
7278 case Instruction::And:
7279 case Instruction::Or:
7280 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007281 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007282 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7283 // Don't insert two casts if they cannot be eliminated. We allow
7284 // two casts to be inserted if the sizes are the same. This could
7285 // only be converting signedness, which is a noop.
7286 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007287 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7288 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007289 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007290 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7291 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007292 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007293 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007294 }
7295 }
7296
7297 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7298 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7299 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007300 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007301 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007302 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007303 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007304 }
7305 break;
7306 case Instruction::SDiv:
7307 case Instruction::UDiv:
7308 case Instruction::SRem:
7309 case Instruction::URem:
7310 // If we are just changing the sign, rewrite.
7311 if (DestBitSize == SrcBitSize) {
7312 // Don't insert two casts if they cannot be eliminated. We allow
7313 // two casts to be inserted if the sizes are the same. This could
7314 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007315 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7316 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007317 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7318 Op0, DestTy, SrcI);
7319 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7320 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007321 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007322 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7323 }
7324 }
7325 break;
7326
7327 case Instruction::Shl:
7328 // Allow changing the sign of the source operand. Do not allow
7329 // changing the size of the shift, UNLESS the shift amount is a
7330 // constant. We must not change variable sized shifts to a smaller
7331 // size, because it is undefined to shift more bits out than exist
7332 // in the value.
7333 if (DestBitSize == SrcBitSize ||
7334 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007335 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7336 Instruction::BitCast : Instruction::Trunc);
7337 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007338 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007339 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007340 }
7341 break;
7342 case Instruction::AShr:
7343 // If this is a signed shr, and if all bits shifted in are about to be
7344 // truncated off, turn it into an unsigned shr to allow greater
7345 // simplifications.
7346 if (DestBitSize < SrcBitSize &&
7347 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007348 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007349 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7350 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007351 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007352 }
7353 }
7354 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007355 }
7356 return 0;
7357}
7358
Chris Lattner8a9f5712007-04-11 06:57:46 +00007359Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007360 if (Instruction *Result = commonIntCastTransforms(CI))
7361 return Result;
7362
7363 Value *Src = CI.getOperand(0);
7364 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007365 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7366 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007367
7368 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7369 switch (SrcI->getOpcode()) {
7370 default: break;
7371 case Instruction::LShr:
7372 // We can shrink lshr to something smaller if we know the bits shifted in
7373 // are already zeros.
7374 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007375 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007376
7377 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007378 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007379 Value* SrcIOp0 = SrcI->getOperand(0);
7380 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007381 if (ShAmt >= DestBitWidth) // All zeros.
7382 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7383
7384 // Okay, we can shrink this. Truncate the input, then return a new
7385 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007386 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7387 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7388 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007389 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007390 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007391 } else { // This is a variable shr.
7392
7393 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7394 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7395 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007396 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007397 Value *One = ConstantInt::get(SrcI->getType(), 1);
7398
Reid Spencer832254e2007-02-02 02:16:23 +00007399 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007400 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007401 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007402 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007403 SrcI->getOperand(0),
7404 "tmp"), CI);
7405 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007406 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007407 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007408 }
7409 break;
7410 }
7411 }
7412
7413 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007414}
7415
Evan Chengb98a10e2008-03-24 00:21:34 +00007416/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7417/// in order to eliminate the icmp.
7418Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7419 bool DoXform) {
7420 // If we are just checking for a icmp eq of a single bit and zext'ing it
7421 // to an integer, then shift the bit to the appropriate place and then
7422 // cast to integer to avoid the comparison.
7423 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7424 const APInt &Op1CV = Op1C->getValue();
7425
7426 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7427 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7428 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7429 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7430 if (!DoXform) return ICI;
7431
7432 Value *In = ICI->getOperand(0);
7433 Value *Sh = ConstantInt::get(In->getType(),
7434 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007435 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007436 In->getName()+".lobit"),
7437 CI);
7438 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007439 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007440 false/*ZExt*/, "tmp", &CI);
7441
7442 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7443 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007444 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007445 In->getName()+".not"),
7446 CI);
7447 }
7448
7449 return ReplaceInstUsesWith(CI, In);
7450 }
7451
7452
7453
7454 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7455 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7456 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7457 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7458 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7459 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7460 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7461 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7462 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7463 // This only works for EQ and NE
7464 ICI->isEquality()) {
7465 // If Op1C some other power of two, convert:
7466 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7467 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7468 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7469 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7470
7471 APInt KnownZeroMask(~KnownZero);
7472 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7473 if (!DoXform) return ICI;
7474
7475 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7476 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7477 // (X&4) == 2 --> false
7478 // (X&4) != 2 --> true
7479 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7480 Res = ConstantExpr::getZExt(Res, CI.getType());
7481 return ReplaceInstUsesWith(CI, Res);
7482 }
7483
7484 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7485 Value *In = ICI->getOperand(0);
7486 if (ShiftAmt) {
7487 // Perform a logical shr by shiftamt.
7488 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007489 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007490 ConstantInt::get(In->getType(), ShiftAmt),
7491 In->getName()+".lobit"), CI);
7492 }
7493
7494 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7495 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007496 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007497 InsertNewInstBefore(cast<Instruction>(In), CI);
7498 }
7499
7500 if (CI.getType() == In->getType())
7501 return ReplaceInstUsesWith(CI, In);
7502 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007503 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007504 }
7505 }
7506 }
7507
7508 return 0;
7509}
7510
Chris Lattner8a9f5712007-04-11 06:57:46 +00007511Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007512 // If one of the common conversion will work ..
7513 if (Instruction *Result = commonIntCastTransforms(CI))
7514 return Result;
7515
7516 Value *Src = CI.getOperand(0);
7517
7518 // If this is a cast of a cast
7519 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007520 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7521 // types and if the sizes are just right we can convert this into a logical
7522 // 'and' which will be much cheaper than the pair of casts.
7523 if (isa<TruncInst>(CSrc)) {
7524 // Get the sizes of the types involved
7525 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007526 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7527 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7528 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007529 // If we're actually extending zero bits and the trunc is a no-op
7530 if (MidSize < DstSize && SrcSize == DstSize) {
7531 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007532 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007533 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007534 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007535 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007536 // Unfortunately, if the type changed, we need to cast it back.
7537 if (And->getType() != CI.getType()) {
7538 And->setName(CSrc->getName()+".mask");
7539 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007540 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007541 }
7542 return And;
7543 }
7544 }
7545 }
7546
Evan Chengb98a10e2008-03-24 00:21:34 +00007547 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7548 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007549
Evan Chengb98a10e2008-03-24 00:21:34 +00007550 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7551 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7552 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7553 // of the (zext icmp) will be transformed.
7554 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7555 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7556 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7557 (transformZExtICmp(LHS, CI, false) ||
7558 transformZExtICmp(RHS, CI, false))) {
7559 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7560 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007561 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007562 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007563 }
7564
Reid Spencer3da59db2006-11-27 01:05:10 +00007565 return 0;
7566}
7567
Chris Lattner8a9f5712007-04-11 06:57:46 +00007568Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007569 if (Instruction *I = commonIntCastTransforms(CI))
7570 return I;
7571
Chris Lattner8a9f5712007-04-11 06:57:46 +00007572 Value *Src = CI.getOperand(0);
7573
7574 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7575 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7576 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7577 // If we are just checking for a icmp eq of a single bit and zext'ing it
7578 // to an integer, then shift the bit to the appropriate place and then
7579 // cast to integer to avoid the comparison.
7580 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7581 const APInt &Op1CV = Op1C->getValue();
7582
7583 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7584 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7585 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7586 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7587 Value *In = ICI->getOperand(0);
7588 Value *Sh = ConstantInt::get(In->getType(),
7589 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007590 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007591 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007592 CI);
7593 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007594 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007595 true/*SExt*/, "tmp", &CI);
7596
7597 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007598 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007599 In->getName()+".not"), CI);
7600
7601 return ReplaceInstUsesWith(CI, In);
7602 }
7603 }
7604 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00007605
7606 // See if the value being truncated is already sign extended. If so, just
7607 // eliminate the trunc/sext pair.
7608 if (getOpcode(Src) == Instruction::Trunc) {
7609 Value *Op = cast<User>(Src)->getOperand(0);
7610 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7611 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7612 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7613 unsigned NumSignBits = ComputeNumSignBits(Op);
7614
7615 if (OpBits == DestBits) {
7616 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7617 // bits, it is already ready.
7618 if (NumSignBits > DestBits-MidBits)
7619 return ReplaceInstUsesWith(CI, Op);
7620 } else if (OpBits < DestBits) {
7621 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7622 // bits, just sext from i32.
7623 if (NumSignBits > OpBits-MidBits)
7624 return new SExtInst(Op, CI.getType(), "tmp");
7625 } else {
7626 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7627 // bits, just truncate to i32.
7628 if (NumSignBits > OpBits-MidBits)
7629 return new TruncInst(Op, CI.getType(), "tmp");
7630 }
7631 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00007632
Chris Lattnerba417832007-04-11 06:12:58 +00007633 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007634}
7635
Chris Lattnerb7530652008-01-27 05:29:54 +00007636/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7637/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007638static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007639 APFloat F = CFP->getValueAPF();
7640 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007641 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007642 return 0;
7643}
7644
7645/// LookThroughFPExtensions - If this is an fp extension instruction, look
7646/// through it until we get the source value.
7647static Value *LookThroughFPExtensions(Value *V) {
7648 if (Instruction *I = dyn_cast<Instruction>(V))
7649 if (I->getOpcode() == Instruction::FPExt)
7650 return LookThroughFPExtensions(I->getOperand(0));
7651
7652 // If this value is a constant, return the constant in the smallest FP type
7653 // that can accurately represent it. This allows us to turn
7654 // (float)((double)X+2.0) into x+2.0f.
7655 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7656 if (CFP->getType() == Type::PPC_FP128Ty)
7657 return V; // No constant folding of this.
7658 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007659 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007660 return V;
7661 if (CFP->getType() == Type::DoubleTy)
7662 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007663 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007664 return V;
7665 // Don't try to shrink to various long double types.
7666 }
7667
7668 return V;
7669}
7670
7671Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7672 if (Instruction *I = commonCastTransforms(CI))
7673 return I;
7674
7675 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7676 // smaller than the destination type, we can eliminate the truncate by doing
7677 // the add as the smaller type. This applies to add/sub/mul/div as well as
7678 // many builtins (sqrt, etc).
7679 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7680 if (OpI && OpI->hasOneUse()) {
7681 switch (OpI->getOpcode()) {
7682 default: break;
7683 case Instruction::Add:
7684 case Instruction::Sub:
7685 case Instruction::Mul:
7686 case Instruction::FDiv:
7687 case Instruction::FRem:
7688 const Type *SrcTy = OpI->getType();
7689 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7690 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7691 if (LHSTrunc->getType() != SrcTy &&
7692 RHSTrunc->getType() != SrcTy) {
7693 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7694 // If the source types were both smaller than the destination type of
7695 // the cast, do this xform.
7696 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7697 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7698 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7699 CI.getType(), CI);
7700 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7701 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007702 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007703 }
7704 }
7705 break;
7706 }
7707 }
7708 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007709}
7710
7711Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7712 return commonCastTransforms(CI);
7713}
7714
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007715Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7716 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7717 // mantissa to accurately represent all values of X. For example, do not
7718 // do this with i64->float->i64.
7719 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7720 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7721 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00007722 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007723 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7724
7725 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007726}
7727
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007728Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7729 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7730 // mantissa to accurately represent all values of X. For example, do not
7731 // do this with i64->float->i64.
7732 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7733 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7734 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00007735 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007736 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7737
7738 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007739}
7740
7741Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7742 return commonCastTransforms(CI);
7743}
7744
7745Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7746 return commonCastTransforms(CI);
7747}
7748
7749Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007750 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007751}
7752
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007753Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7754 if (Instruction *I = commonCastTransforms(CI))
7755 return I;
7756
7757 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7758 if (!DestPointee->isSized()) return 0;
7759
7760 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7761 ConstantInt *Cst;
7762 Value *X;
7763 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7764 m_ConstantInt(Cst)))) {
7765 // If the source and destination operands have the same type, see if this
7766 // is a single-index GEP.
7767 if (X->getType() == CI.getType()) {
7768 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007769 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007770
7771 // Convert the constant to intptr type.
7772 APInt Offset = Cst->getValue();
7773 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7774
7775 // If Offset is evenly divisible by Size, we can do this xform.
7776 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7777 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007778 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007779 }
7780 }
7781 // TODO: Could handle other cases, e.g. where add is indexing into field of
7782 // struct etc.
7783 } else if (CI.getOperand(0)->hasOneUse() &&
7784 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7785 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7786 // "inttoptr+GEP" instead of "add+intptr".
7787
7788 // Get the size of the pointee type.
7789 uint64_t Size = TD->getABITypeSize(DestPointee);
7790
7791 // Convert the constant to intptr type.
7792 APInt Offset = Cst->getValue();
7793 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7794
7795 // If Offset is evenly divisible by Size, we can do this xform.
7796 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7797 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7798
7799 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7800 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007801 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007802 }
7803 }
7804 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007805}
7806
Chris Lattnerd3e28342007-04-27 17:44:50 +00007807Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007808 // If the operands are integer typed then apply the integer transforms,
7809 // otherwise just apply the common ones.
7810 Value *Src = CI.getOperand(0);
7811 const Type *SrcTy = Src->getType();
7812 const Type *DestTy = CI.getType();
7813
Chris Lattner42a75512007-01-15 02:27:26 +00007814 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007815 if (Instruction *Result = commonIntCastTransforms(CI))
7816 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007817 } else if (isa<PointerType>(SrcTy)) {
7818 if (Instruction *I = commonPointerCastTransforms(CI))
7819 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007820 } else {
7821 if (Instruction *Result = commonCastTransforms(CI))
7822 return Result;
7823 }
7824
7825
7826 // Get rid of casts from one type to the same type. These are useless and can
7827 // be replaced by the operand.
7828 if (DestTy == Src->getType())
7829 return ReplaceInstUsesWith(CI, Src);
7830
Reid Spencer3da59db2006-11-27 01:05:10 +00007831 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007832 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7833 const Type *DstElTy = DstPTy->getElementType();
7834 const Type *SrcElTy = SrcPTy->getElementType();
7835
Nate Begeman83ad90a2008-03-31 00:22:16 +00007836 // If the address spaces don't match, don't eliminate the bitcast, which is
7837 // required for changing types.
7838 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7839 return 0;
7840
Chris Lattnerd3e28342007-04-27 17:44:50 +00007841 // If we are casting a malloc or alloca to a pointer to a type of the same
7842 // size, rewrite the allocation instruction to allocate the "right" type.
7843 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7844 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7845 return V;
7846
Chris Lattnerd717c182007-05-05 22:32:24 +00007847 // If the source and destination are pointers, and this cast is equivalent
7848 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007849 // This can enhance SROA and other transforms that want type-safe pointers.
7850 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7851 unsigned NumZeros = 0;
7852 while (SrcElTy != DstElTy &&
7853 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7854 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7855 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7856 ++NumZeros;
7857 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007858
Chris Lattnerd3e28342007-04-27 17:44:50 +00007859 // If we found a path from the src to dest, create the getelementptr now.
7860 if (SrcElTy == DstElTy) {
7861 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007862 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7863 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007864 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007865 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007866
Reid Spencer3da59db2006-11-27 01:05:10 +00007867 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7868 if (SVI->hasOneUse()) {
7869 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7870 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007871 if (isa<VectorType>(DestTy) &&
7872 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007873 SVI->getType()->getNumElements()) {
7874 CastInst *Tmp;
7875 // If either of the operands is a cast from CI.getType(), then
7876 // evaluating the shuffle in the casted destination's type will allow
7877 // us to eliminate at least one cast.
7878 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7879 Tmp->getOperand(0)->getType() == DestTy) ||
7880 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7881 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007882 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7883 SVI->getOperand(0), DestTy, &CI);
7884 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7885 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007886 // Return a new shuffle vector. Use the same element ID's, as we
7887 // know the vector types match #elts.
7888 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007889 }
7890 }
7891 }
7892 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007893 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007894}
7895
Chris Lattnere576b912004-04-09 23:46:01 +00007896/// GetSelectFoldableOperands - We want to turn code that looks like this:
7897/// %C = or %A, %B
7898/// %D = select %cond, %C, %A
7899/// into:
7900/// %C = select %cond, %B, 0
7901/// %D = or %A, %C
7902///
7903/// Assuming that the specified instruction is an operand to the select, return
7904/// a bitmask indicating which operands of this instruction are foldable if they
7905/// equal the other incoming value of the select.
7906///
7907static unsigned GetSelectFoldableOperands(Instruction *I) {
7908 switch (I->getOpcode()) {
7909 case Instruction::Add:
7910 case Instruction::Mul:
7911 case Instruction::And:
7912 case Instruction::Or:
7913 case Instruction::Xor:
7914 return 3; // Can fold through either operand.
7915 case Instruction::Sub: // Can only fold on the amount subtracted.
7916 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007917 case Instruction::LShr:
7918 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007919 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007920 default:
7921 return 0; // Cannot fold
7922 }
7923}
7924
7925/// GetSelectFoldableConstant - For the same transformation as the previous
7926/// function, return the identity constant that goes into the select.
7927static Constant *GetSelectFoldableConstant(Instruction *I) {
7928 switch (I->getOpcode()) {
7929 default: assert(0 && "This cannot happen!"); abort();
7930 case Instruction::Add:
7931 case Instruction::Sub:
7932 case Instruction::Or:
7933 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007934 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007935 case Instruction::LShr:
7936 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007937 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007938 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007939 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007940 case Instruction::Mul:
7941 return ConstantInt::get(I->getType(), 1);
7942 }
7943}
7944
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007945/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7946/// have the same opcode and only one use each. Try to simplify this.
7947Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7948 Instruction *FI) {
7949 if (TI->getNumOperands() == 1) {
7950 // If this is a non-volatile load or a cast from the same type,
7951 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007952 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007953 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7954 return 0;
7955 } else {
7956 return 0; // unknown unary op.
7957 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007958
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007959 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00007960 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7961 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007962 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007963 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00007964 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007965 }
7966
Reid Spencer832254e2007-02-02 02:16:23 +00007967 // Only handle binary operators here.
7968 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007969 return 0;
7970
7971 // Figure out if the operations have any operands in common.
7972 Value *MatchOp, *OtherOpT, *OtherOpF;
7973 bool MatchIsOpZero;
7974 if (TI->getOperand(0) == FI->getOperand(0)) {
7975 MatchOp = TI->getOperand(0);
7976 OtherOpT = TI->getOperand(1);
7977 OtherOpF = FI->getOperand(1);
7978 MatchIsOpZero = true;
7979 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7980 MatchOp = TI->getOperand(1);
7981 OtherOpT = TI->getOperand(0);
7982 OtherOpF = FI->getOperand(0);
7983 MatchIsOpZero = false;
7984 } else if (!TI->isCommutative()) {
7985 return 0;
7986 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7987 MatchOp = TI->getOperand(0);
7988 OtherOpT = TI->getOperand(1);
7989 OtherOpF = FI->getOperand(0);
7990 MatchIsOpZero = true;
7991 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7992 MatchOp = TI->getOperand(1);
7993 OtherOpT = TI->getOperand(0);
7994 OtherOpF = FI->getOperand(1);
7995 MatchIsOpZero = true;
7996 } else {
7997 return 0;
7998 }
7999
8000 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008001 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8002 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008003 InsertNewInstBefore(NewSI, SI);
8004
8005 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8006 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008007 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008008 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008009 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008010 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008011 assert(0 && "Shouldn't get here");
8012 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008013}
8014
Chris Lattner3d69f462004-03-12 05:52:32 +00008015Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008016 Value *CondVal = SI.getCondition();
8017 Value *TrueVal = SI.getTrueValue();
8018 Value *FalseVal = SI.getFalseValue();
8019
8020 // select true, X, Y -> X
8021 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008022 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008023 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008024
8025 // select C, X, X -> X
8026 if (TrueVal == FalseVal)
8027 return ReplaceInstUsesWith(SI, TrueVal);
8028
Chris Lattnere87597f2004-10-16 18:11:37 +00008029 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8030 return ReplaceInstUsesWith(SI, FalseVal);
8031 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8032 return ReplaceInstUsesWith(SI, TrueVal);
8033 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8034 if (isa<Constant>(TrueVal))
8035 return ReplaceInstUsesWith(SI, TrueVal);
8036 else
8037 return ReplaceInstUsesWith(SI, FalseVal);
8038 }
8039
Reid Spencer4fe16d62007-01-11 18:21:29 +00008040 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008041 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008042 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008043 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008044 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008045 } else {
8046 // Change: A = select B, false, C --> A = and !B, C
8047 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008048 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008049 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008050 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008051 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008052 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008053 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008054 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008055 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008056 } else {
8057 // Change: A = select B, C, true --> A = or !B, C
8058 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008059 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008060 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008061 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008062 }
8063 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008064
8065 // select a, b, a -> a&b
8066 // select a, a, b -> a|b
8067 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008068 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008069 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008070 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008071 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008072
Chris Lattner2eefe512004-04-09 19:05:30 +00008073 // Selecting between two integer constants?
8074 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8075 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008076 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008077 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008078 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008079 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008080 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008081 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008082 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008083 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008084 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008085 }
Chris Lattnerba417832007-04-11 06:12:58 +00008086
8087 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008088
Reid Spencere4d87aa2006-12-23 06:05:41 +00008089 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008090
Reid Spencere4d87aa2006-12-23 06:05:41 +00008091 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008092 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008093 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008094 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008095 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008096 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008097 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008098 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008099 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008100 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008101 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008102 InsertNewInstBefore(SRA, SI);
8103
Reid Spencer3da59db2006-11-27 01:05:10 +00008104 // Finally, convert to the type of the select RHS. We figure out
8105 // if this requires a SExt, Trunc or BitCast based on the sizes.
8106 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008107 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8108 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008109 if (SRASize < SISize)
8110 opc = Instruction::SExt;
8111 else if (SRASize > SISize)
8112 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008113 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008114 }
8115 }
8116
8117
8118 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008119 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008120 // non-constant value, eliminate this whole mess. This corresponds to
8121 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008122 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008123 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008124 cast<Constant>(IC->getOperand(1))->isNullValue())
8125 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8126 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008127 isa<ConstantInt>(ICA->getOperand(1)) &&
8128 (ICA->getOperand(1) == TrueValC ||
8129 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008130 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8131 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008132 // know whether we have a icmp_ne or icmp_eq and whether the
8133 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008134 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008135 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008136 Value *V = ICA;
8137 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008138 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008139 Instruction::Xor, V, ICA->getOperand(1)), SI);
8140 return ReplaceInstUsesWith(SI, V);
8141 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008142 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008143 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008144
8145 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008146 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8147 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008148 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008149 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8150 // This is not safe in general for floating point:
8151 // consider X== -0, Y== +0.
8152 // It becomes safe if either operand is a nonzero constant.
8153 ConstantFP *CFPt, *CFPf;
8154 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8155 !CFPt->getValueAPF().isZero()) ||
8156 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8157 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008158 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008159 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008160 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008161 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008162 return ReplaceInstUsesWith(SI, TrueVal);
8163 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8164
Reid Spencere4d87aa2006-12-23 06:05:41 +00008165 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008166 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008167 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8168 // This is not safe in general for floating point:
8169 // consider X== -0, Y== +0.
8170 // It becomes safe if either operand is a nonzero constant.
8171 ConstantFP *CFPt, *CFPf;
8172 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8173 !CFPt->getValueAPF().isZero()) ||
8174 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8175 !CFPf->getValueAPF().isZero()))
8176 return ReplaceInstUsesWith(SI, FalseVal);
8177 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008178 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008179 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8180 return ReplaceInstUsesWith(SI, TrueVal);
8181 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8182 }
8183 }
8184
8185 // See if we are selecting two values based on a comparison of the two values.
8186 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8187 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8188 // Transform (X == Y) ? X : Y -> Y
8189 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8190 return ReplaceInstUsesWith(SI, FalseVal);
8191 // Transform (X != Y) ? X : Y -> X
8192 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8193 return ReplaceInstUsesWith(SI, TrueVal);
8194 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8195
8196 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8197 // Transform (X == Y) ? Y : X -> X
8198 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8199 return ReplaceInstUsesWith(SI, FalseVal);
8200 // Transform (X != Y) ? Y : X -> Y
8201 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008202 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008203 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8204 }
8205 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008206
Chris Lattner87875da2005-01-13 22:52:24 +00008207 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8208 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8209 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008210 Instruction *AddOp = 0, *SubOp = 0;
8211
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008212 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8213 if (TI->getOpcode() == FI->getOpcode())
8214 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8215 return IV;
8216
8217 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8218 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008219 if (TI->getOpcode() == Instruction::Sub &&
8220 FI->getOpcode() == Instruction::Add) {
8221 AddOp = FI; SubOp = TI;
8222 } else if (FI->getOpcode() == Instruction::Sub &&
8223 TI->getOpcode() == Instruction::Add) {
8224 AddOp = TI; SubOp = FI;
8225 }
8226
8227 if (AddOp) {
8228 Value *OtherAddOp = 0;
8229 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8230 OtherAddOp = AddOp->getOperand(1);
8231 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8232 OtherAddOp = AddOp->getOperand(0);
8233 }
8234
8235 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008236 // So at this point we know we have (Y -> OtherAddOp):
8237 // select C, (add X, Y), (sub X, Z)
8238 Value *NegVal; // Compute -Z
8239 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8240 NegVal = ConstantExpr::getNeg(C);
8241 } else {
8242 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008243 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008244 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008245
8246 Value *NewTrueOp = OtherAddOp;
8247 Value *NewFalseOp = NegVal;
8248 if (AddOp != TI)
8249 std::swap(NewTrueOp, NewFalseOp);
8250 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008251 SelectInst::Create(CondVal, NewTrueOp,
8252 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008253
8254 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008255 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008256 }
8257 }
8258 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008259
Chris Lattnere576b912004-04-09 23:46:01 +00008260 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008261 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008262 // See the comment above GetSelectFoldableOperands for a description of the
8263 // transformation we are doing here.
8264 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8265 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8266 !isa<Constant>(FalseVal))
8267 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8268 unsigned OpToFold = 0;
8269 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8270 OpToFold = 1;
8271 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8272 OpToFold = 2;
8273 }
8274
8275 if (OpToFold) {
8276 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008277 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008278 SelectInst::Create(SI.getCondition(),
8279 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008280 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008281 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008282 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008283 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008284 else {
8285 assert(0 && "Unknown instruction!!");
8286 }
8287 }
8288 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008289
Chris Lattnere576b912004-04-09 23:46:01 +00008290 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8291 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8292 !isa<Constant>(TrueVal))
8293 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8294 unsigned OpToFold = 0;
8295 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8296 OpToFold = 1;
8297 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8298 OpToFold = 2;
8299 }
8300
8301 if (OpToFold) {
8302 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008303 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008304 SelectInst::Create(SI.getCondition(), C,
8305 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008306 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008307 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008308 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008309 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008310 else
Chris Lattnere576b912004-04-09 23:46:01 +00008311 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008312 }
8313 }
8314 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008315
8316 if (BinaryOperator::isNot(CondVal)) {
8317 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8318 SI.setOperand(1, FalseVal);
8319 SI.setOperand(2, TrueVal);
8320 return &SI;
8321 }
8322
Chris Lattner3d69f462004-03-12 05:52:32 +00008323 return 0;
8324}
8325
Dan Gohmaneee962e2008-04-10 18:43:06 +00008326/// EnforceKnownAlignment - If the specified pointer points to an object that
8327/// we control, modify the object's alignment to PrefAlign. This isn't
8328/// often possible though. If alignment is important, a more reliable approach
8329/// is to simply align all global variables and allocation instructions to
8330/// their preferred alignment from the beginning.
8331///
8332static unsigned EnforceKnownAlignment(Value *V,
8333 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008334
Dan Gohmaneee962e2008-04-10 18:43:06 +00008335 User *U = dyn_cast<User>(V);
8336 if (!U) return Align;
8337
8338 switch (getOpcode(U)) {
8339 default: break;
8340 case Instruction::BitCast:
8341 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8342 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008343 // If all indexes are zero, it is just the alignment of the base pointer.
8344 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00008345 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00008346 if (!isa<Constant>(*i) ||
8347 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008348 AllZeroOperands = false;
8349 break;
8350 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008351
8352 if (AllZeroOperands) {
8353 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008354 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008355 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008356 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008357 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008358 }
8359
8360 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8361 // If there is a large requested alignment and we can, bump up the alignment
8362 // of the global.
8363 if (!GV->isDeclaration()) {
8364 GV->setAlignment(PrefAlign);
8365 Align = PrefAlign;
8366 }
8367 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8368 // If there is a requested alignment and if this is an alloca, round up. We
8369 // don't do this for malloc, because some systems can't respect the request.
8370 if (isa<AllocaInst>(AI)) {
8371 AI->setAlignment(PrefAlign);
8372 Align = PrefAlign;
8373 }
8374 }
8375
8376 return Align;
8377}
8378
8379/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8380/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8381/// and it is more than the alignment of the ultimate object, see if we can
8382/// increase the alignment of the ultimate object, making this check succeed.
8383unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8384 unsigned PrefAlign) {
8385 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8386 sizeof(PrefAlign) * CHAR_BIT;
8387 APInt Mask = APInt::getAllOnesValue(BitWidth);
8388 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8389 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8390 unsigned TrailZ = KnownZero.countTrailingOnes();
8391 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8392
8393 if (PrefAlign > Align)
8394 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8395
8396 // We don't need to make any adjustment.
8397 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008398}
8399
Chris Lattnerf497b022008-01-13 23:50:23 +00008400Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008401 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8402 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008403 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8404 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8405
8406 if (CopyAlign < MinAlign) {
8407 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8408 return MI;
8409 }
8410
8411 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8412 // load/store.
8413 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8414 if (MemOpLength == 0) return 0;
8415
Chris Lattner37ac6082008-01-14 00:28:35 +00008416 // Source and destination pointer types are always "i8*" for intrinsic. See
8417 // if the size is something we can handle with a single primitive load/store.
8418 // A single load+store correctly handles overlapping memory in the memmove
8419 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008420 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008421 if (Size == 0) return MI; // Delete this mem transfer.
8422
8423 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008424 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008425
Chris Lattner37ac6082008-01-14 00:28:35 +00008426 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008427 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008428
8429 // Memcpy forces the use of i8* for the source and destination. That means
8430 // that if you're using memcpy to move one double around, you'll get a cast
8431 // from double* to i8*. We'd much rather use a double load+store rather than
8432 // an i64 load+store, here because this improves the odds that the source or
8433 // dest address will be promotable. See if we can find a better type than the
8434 // integer datatype.
8435 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8436 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8437 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8438 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8439 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00008440 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00008441 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8442 if (STy->getNumElements() == 1)
8443 SrcETy = STy->getElementType(0);
8444 else
8445 break;
8446 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8447 if (ATy->getNumElements() == 1)
8448 SrcETy = ATy->getElementType();
8449 else
8450 break;
8451 } else
8452 break;
8453 }
8454
Dan Gohman8f8e2692008-05-23 01:52:21 +00008455 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00008456 NewPtrTy = PointerType::getUnqual(SrcETy);
8457 }
8458 }
8459
8460
Chris Lattnerf497b022008-01-13 23:50:23 +00008461 // If the memcpy/memmove provides better alignment info than we can
8462 // infer, use it.
8463 SrcAlign = std::max(SrcAlign, CopyAlign);
8464 DstAlign = std::max(DstAlign, CopyAlign);
8465
8466 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8467 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008468 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8469 InsertNewInstBefore(L, *MI);
8470 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8471
8472 // Set the size of the copy to 0, it will be deleted on the next iteration.
8473 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8474 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008475}
Chris Lattner3d69f462004-03-12 05:52:32 +00008476
Chris Lattner69ea9d22008-04-30 06:39:11 +00008477Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8478 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8479 if (MI->getAlignment()->getZExtValue() < Alignment) {
8480 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8481 return MI;
8482 }
8483
8484 // Extract the length and alignment and fill if they are constant.
8485 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8486 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8487 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8488 return 0;
8489 uint64_t Len = LenC->getZExtValue();
8490 Alignment = MI->getAlignment()->getZExtValue();
8491
8492 // If the length is zero, this is a no-op
8493 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8494
8495 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8496 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8497 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8498
8499 Value *Dest = MI->getDest();
8500 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8501
8502 // Alignment 0 is identity for alignment 1 for memset, but not store.
8503 if (Alignment == 0) Alignment = 1;
8504
8505 // Extract the fill value and store.
8506 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8507 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8508 Alignment), *MI);
8509
8510 // Set the size of the copy to 0, it will be deleted on the next iteration.
8511 MI->setLength(Constant::getNullValue(LenC->getType()));
8512 return MI;
8513 }
8514
8515 return 0;
8516}
8517
8518
Chris Lattner8b0ea312006-01-13 20:11:04 +00008519/// visitCallInst - CallInst simplification. This mostly only handles folding
8520/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8521/// the heavy lifting.
8522///
Chris Lattner9fe38862003-06-19 17:00:31 +00008523Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008524 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8525 if (!II) return visitCallSite(&CI);
8526
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008527 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8528 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008529 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008530 bool Changed = false;
8531
8532 // memmove/cpy/set of zero bytes is a noop.
8533 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8534 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8535
Chris Lattner35b9e482004-10-12 04:52:52 +00008536 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008537 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008538 // Replace the instruction with just byte operations. We would
8539 // transform other cases to loads/stores, but we don't know if
8540 // alignment is sufficient.
8541 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008542 }
8543
Chris Lattner35b9e482004-10-12 04:52:52 +00008544 // If we have a memmove and the source operation is a constant global,
8545 // then the source and dest pointers can't alias, so we can change this
8546 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008547 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008548 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8549 if (GVSrc->isConstant()) {
8550 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008551 Intrinsic::ID MemCpyID;
8552 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8553 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008554 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008555 MemCpyID = Intrinsic::memcpy_i64;
8556 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008557 Changed = true;
8558 }
Chris Lattnera935db82008-05-28 05:30:41 +00008559
8560 // memmove(x,x,size) -> noop.
8561 if (MMI->getSource() == MMI->getDest())
8562 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00008563 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008564
Chris Lattner95a959d2006-03-06 20:18:44 +00008565 // If we can determine a pointer alignment that is bigger than currently
8566 // set, update the alignment.
8567 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008568 if (Instruction *I = SimplifyMemTransfer(MI))
8569 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008570 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8571 if (Instruction *I = SimplifyMemSet(MSI))
8572 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008573 }
8574
Chris Lattner8b0ea312006-01-13 20:11:04 +00008575 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00008576 }
8577
8578 switch (II->getIntrinsicID()) {
8579 default: break;
8580 case Intrinsic::bswap:
8581 // bswap(bswap(x)) -> x
8582 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8583 if (Operand->getIntrinsicID() == Intrinsic::bswap)
8584 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8585 break;
8586 case Intrinsic::ppc_altivec_lvx:
8587 case Intrinsic::ppc_altivec_lvxl:
8588 case Intrinsic::x86_sse_loadu_ps:
8589 case Intrinsic::x86_sse2_loadu_pd:
8590 case Intrinsic::x86_sse2_loadu_dq:
8591 // Turn PPC lvx -> load if the pointer is known aligned.
8592 // Turn X86 loadups -> load if the pointer is known aligned.
8593 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8594 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8595 PointerType::getUnqual(II->getType()),
8596 CI);
8597 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00008598 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008599 break;
8600 case Intrinsic::ppc_altivec_stvx:
8601 case Intrinsic::ppc_altivec_stvxl:
8602 // Turn stvx -> store if the pointer is known aligned.
8603 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8604 const Type *OpPtrTy =
8605 PointerType::getUnqual(II->getOperand(1)->getType());
8606 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8607 return new StoreInst(II->getOperand(1), Ptr);
8608 }
8609 break;
8610 case Intrinsic::x86_sse_storeu_ps:
8611 case Intrinsic::x86_sse2_storeu_pd:
8612 case Intrinsic::x86_sse2_storeu_dq:
8613 case Intrinsic::x86_sse2_storel_dq:
8614 // Turn X86 storeu -> store if the pointer is known aligned.
8615 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8616 const Type *OpPtrTy =
8617 PointerType::getUnqual(II->getOperand(2)->getType());
8618 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8619 return new StoreInst(II->getOperand(2), Ptr);
8620 }
8621 break;
8622
8623 case Intrinsic::x86_sse_cvttss2si: {
8624 // These intrinsics only demands the 0th element of its input vector. If
8625 // we can simplify the input based on that, do so now.
8626 uint64_t UndefElts;
8627 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8628 UndefElts)) {
8629 II->setOperand(1, V);
8630 return II;
8631 }
8632 break;
8633 }
8634
8635 case Intrinsic::ppc_altivec_vperm:
8636 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8637 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8638 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00008639
Chris Lattner0521e3c2008-06-18 04:33:20 +00008640 // Check that all of the elements are integer constants or undefs.
8641 bool AllEltsOk = true;
8642 for (unsigned i = 0; i != 16; ++i) {
8643 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8644 !isa<UndefValue>(Mask->getOperand(i))) {
8645 AllEltsOk = false;
8646 break;
8647 }
8648 }
8649
8650 if (AllEltsOk) {
8651 // Cast the input vectors to byte vectors.
8652 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8653 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8654 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008655
Chris Lattner0521e3c2008-06-18 04:33:20 +00008656 // Only extract each element once.
8657 Value *ExtractedElts[32];
8658 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8659
Chris Lattnere2ed0572006-04-06 19:19:17 +00008660 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00008661 if (isa<UndefValue>(Mask->getOperand(i)))
8662 continue;
8663 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8664 Idx &= 31; // Match the hardware behavior.
8665
8666 if (ExtractedElts[Idx] == 0) {
8667 Instruction *Elt =
8668 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8669 InsertNewInstBefore(Elt, CI);
8670 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00008671 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00008672
Chris Lattner0521e3c2008-06-18 04:33:20 +00008673 // Insert this value into the result vector.
8674 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8675 i, "tmp");
8676 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008677 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008678 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008679 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008680 }
8681 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00008682
Chris Lattner0521e3c2008-06-18 04:33:20 +00008683 case Intrinsic::stackrestore: {
8684 // If the save is right next to the restore, remove the restore. This can
8685 // happen when variable allocas are DCE'd.
8686 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8687 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8688 BasicBlock::iterator BI = SS;
8689 if (&*++BI == II)
8690 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008691 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008692 }
8693
8694 // Scan down this block to see if there is another stack restore in the
8695 // same block without an intervening call/alloca.
8696 BasicBlock::iterator BI = II;
8697 TerminatorInst *TI = II->getParent()->getTerminator();
8698 bool CannotRemove = false;
8699 for (++BI; &*BI != TI; ++BI) {
8700 if (isa<AllocaInst>(BI)) {
8701 CannotRemove = true;
8702 break;
8703 }
8704 if (isa<CallInst>(BI)) {
8705 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008706 CannotRemove = true;
8707 break;
8708 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008709 // If there is a stackrestore below this one, remove this one.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008710 return EraseInstFromFunction(CI);
Chris Lattner0521e3c2008-06-18 04:33:20 +00008711 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008712 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00008713
8714 // If the stack restore is in a return/unwind block and if there are no
8715 // allocas or calls between the restore and the return, nuke the restore.
8716 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8717 return EraseInstFromFunction(CI);
8718 break;
8719 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008720 }
8721
Chris Lattner8b0ea312006-01-13 20:11:04 +00008722 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008723}
8724
8725// InvokeInst simplification
8726//
8727Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008728 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008729}
8730
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008731/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8732/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008733static bool isSafeToEliminateVarargsCast(const CallSite CS,
8734 const CastInst * const CI,
8735 const TargetData * const TD,
8736 const int ix) {
8737 if (!CI->isLosslessCast())
8738 return false;
8739
8740 // The size of ByVal arguments is derived from the type, so we
8741 // can't change to a type with a different size. If the size were
8742 // passed explicitly we could avoid this check.
8743 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8744 return true;
8745
8746 const Type* SrcTy =
8747 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8748 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8749 if (!SrcTy->isSized() || !DstTy->isSized())
8750 return false;
8751 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8752 return false;
8753 return true;
8754}
8755
Chris Lattnera44d8a22003-10-07 22:32:43 +00008756// visitCallSite - Improvements for call and invoke instructions.
8757//
8758Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008759 bool Changed = false;
8760
8761 // If the callee is a constexpr cast of a function, attempt to move the cast
8762 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008763 if (transformConstExprCastCall(CS)) return 0;
8764
Chris Lattner6c266db2003-10-07 22:54:13 +00008765 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008766
Chris Lattner08b22ec2005-05-13 07:09:09 +00008767 if (Function *CalleeF = dyn_cast<Function>(Callee))
8768 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8769 Instruction *OldCall = CS.getInstruction();
8770 // If the call and callee calling conventions don't match, this call must
8771 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008772 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008773 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8774 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008775 if (!OldCall->use_empty())
8776 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8777 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8778 return EraseInstFromFunction(*OldCall);
8779 return 0;
8780 }
8781
Chris Lattner17be6352004-10-18 02:59:09 +00008782 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8783 // This instruction is not reachable, just remove it. We insert a store to
8784 // undef so that we know that this code is not reachable, despite the fact
8785 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008786 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008787 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008788 CS.getInstruction());
8789
8790 if (!CS.getInstruction()->use_empty())
8791 CS.getInstruction()->
8792 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8793
8794 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8795 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008796 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8797 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008798 }
Chris Lattner17be6352004-10-18 02:59:09 +00008799 return EraseInstFromFunction(*CS.getInstruction());
8800 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008801
Duncan Sandscdb6d922007-09-17 10:26:40 +00008802 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8803 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8804 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8805 return transformCallThroughTrampoline(CS);
8806
Chris Lattner6c266db2003-10-07 22:54:13 +00008807 const PointerType *PTy = cast<PointerType>(Callee->getType());
8808 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8809 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00008810 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00008811 // See if we can optimize any arguments passed through the varargs area of
8812 // the call.
8813 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00008814 E = CS.arg_end(); I != E; ++I, ++ix) {
8815 CastInst *CI = dyn_cast<CastInst>(*I);
8816 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8817 *I = CI->getOperand(0);
8818 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00008819 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00008820 }
Chris Lattner6c266db2003-10-07 22:54:13 +00008821 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008822
Duncan Sandsf0c33542007-12-19 21:13:37 +00008823 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008824 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008825 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008826 Changed = true;
8827 }
8828
Chris Lattner6c266db2003-10-07 22:54:13 +00008829 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008830}
8831
Chris Lattner9fe38862003-06-19 17:00:31 +00008832// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8833// attempt to move the cast to the arguments of the call/invoke.
8834//
8835bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8836 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8837 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008838 if (CE->getOpcode() != Instruction::BitCast ||
8839 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008840 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008841 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008842 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008843 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008844
8845 // Okay, this is a cast from a function to a different type. Unless doing so
8846 // would cause a type conversion of one of our arguments, change this call to
8847 // be a direct call with arguments casted to the appropriate types.
8848 //
8849 const FunctionType *FT = Callee->getFunctionType();
8850 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008851 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00008852
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008853 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00008854 return false; // TODO: Handle multiple return values.
8855
Chris Lattnerf78616b2004-01-14 06:06:08 +00008856 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008857 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00008858 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008859 // Conversion is ok if changing from one pointer type to another or from
8860 // a pointer to an integer of the same size.
8861 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00008862 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00008863 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008864
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008865 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008866 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008867 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008868 return false; // Cannot transform this return value.
8869
Chris Lattner58d74912008-03-12 17:45:29 +00008870 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8871 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008872 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00008873 return false; // Attribute not compatible with transformed value.
8874 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008875
Chris Lattnerf78616b2004-01-14 06:06:08 +00008876 // If the callsite is an invoke instruction, and the return value is used by
8877 // a PHI node in a successor, we cannot change the return type of the call
8878 // because there is no place to put the cast instruction (without breaking
8879 // the critical edge). Bail out in this case.
8880 if (!Caller->use_empty())
8881 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8882 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8883 UI != E; ++UI)
8884 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8885 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008886 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008887 return false;
8888 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008889
8890 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8891 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008892
Chris Lattner9fe38862003-06-19 17:00:31 +00008893 CallSite::arg_iterator AI = CS.arg_begin();
8894 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8895 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008896 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008897
8898 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008899 return false; // Cannot transform this parameter value.
8900
Chris Lattner58d74912008-03-12 17:45:29 +00008901 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8902 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008903
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008904 // Converting from one pointer type to another or between a pointer and an
8905 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00008906 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008907 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8908 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00008909 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008910 }
8911
8912 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008913 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008914 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008915
Chris Lattner58d74912008-03-12 17:45:29 +00008916 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8917 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008918 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008919 // won't be dropping them. Check that these extra arguments have attributes
8920 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008921 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8922 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008923 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008924 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008925 if (PAttrs & ParamAttr::VarArgsIncompatible)
8926 return false;
8927 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008928
Chris Lattner9fe38862003-06-19 17:00:31 +00008929 // Okay, we decided that this is a safe thing to do: go ahead and start
8930 // inserting cast instructions as necessary...
8931 std::vector<Value*> Args;
8932 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008933 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008934 attrVec.reserve(NumCommonArgs);
8935
8936 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008937 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008938
8939 // If the return value is not being used, the type may not be compatible
8940 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008941 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008942
8943 // Add the new return attributes.
8944 if (RAttrs)
8945 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008946
8947 AI = CS.arg_begin();
8948 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8949 const Type *ParamTy = FT->getParamType(i);
8950 if ((*AI)->getType() == ParamTy) {
8951 Args.push_back(*AI);
8952 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008953 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008954 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008955 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008956 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008957 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008958
8959 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008960 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008961 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008962 }
8963
8964 // If the function takes more arguments than the call was taking, add them
8965 // now...
8966 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8967 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8968
8969 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008970 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008971 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008972 cerr << "WARNING: While resolving call to function '"
8973 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008974 } else {
8975 // Add all of the arguments in their promoted form to the arg list...
8976 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8977 const Type *PTy = getPromotedType((*AI)->getType());
8978 if (PTy != (*AI)->getType()) {
8979 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008980 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8981 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008982 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008983 InsertNewInstBefore(Cast, *Caller);
8984 Args.push_back(Cast);
8985 } else {
8986 Args.push_back(*AI);
8987 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008988
Duncan Sandse1e520f2008-01-13 08:02:44 +00008989 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008990 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00008991 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8992 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008993 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008994 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008995
Duncan Sandsf413cdf2008-06-01 07:38:42 +00008996 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008997 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008998
Chris Lattner58d74912008-03-12 17:45:29 +00008999 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009000
Chris Lattner9fe38862003-06-19 17:00:31 +00009001 Instruction *NC;
9002 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009003 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009004 Args.begin(), Args.end(),
9005 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009006 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009007 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009008 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009009 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9010 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009011 CallInst *CI = cast<CallInst>(Caller);
9012 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009013 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009014 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009015 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009016 }
9017
Chris Lattner6934a042007-02-11 01:23:03 +00009018 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009019 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009020 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009021 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009022 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009023 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009024 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009025
9026 // If this is an invoke instruction, we should insert it after the first
9027 // non-phi, instruction in the normal successor block.
9028 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009029 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009030 InsertNewInstBefore(NC, *I);
9031 } else {
9032 // Otherwise, it's a call, just insert cast right after the call instr
9033 InsertNewInstBefore(NC, *Caller);
9034 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009035 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009036 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009037 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009038 }
9039 }
9040
9041 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9042 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009043 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009044 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009045 return true;
9046}
9047
Duncan Sandscdb6d922007-09-17 10:26:40 +00009048// transformCallThroughTrampoline - Turn a call to a function created by the
9049// init_trampoline intrinsic into a direct call to the underlying function.
9050//
9051Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9052 Value *Callee = CS.getCalledValue();
9053 const PointerType *PTy = cast<PointerType>(Callee->getType());
9054 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009055 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009056
9057 // If the call already has the 'nest' attribute somewhere then give up -
9058 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009059 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009060 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009061
9062 IntrinsicInst *Tramp =
9063 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9064
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009065 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009066 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9067 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9068
Chris Lattner58d74912008-03-12 17:45:29 +00009069 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9070 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009071 unsigned NestIdx = 1;
9072 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009073 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009074
9075 // Look for a parameter marked with the 'nest' attribute.
9076 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9077 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009078 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009079 // Record the parameter type and any other attributes.
9080 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009081 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009082 break;
9083 }
9084
9085 if (NestTy) {
9086 Instruction *Caller = CS.getInstruction();
9087 std::vector<Value*> NewArgs;
9088 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9089
Chris Lattner58d74912008-03-12 17:45:29 +00009090 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9091 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009092
Duncan Sandscdb6d922007-09-17 10:26:40 +00009093 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009094 // mean appending it. Likewise for attributes.
9095
9096 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009097 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9098 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009099
Duncan Sandscdb6d922007-09-17 10:26:40 +00009100 {
9101 unsigned Idx = 1;
9102 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9103 do {
9104 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009105 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009106 Value *NestVal = Tramp->getOperand(3);
9107 if (NestVal->getType() != NestTy)
9108 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9109 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009110 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009111 }
9112
9113 if (I == E)
9114 break;
9115
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009116 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009117 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009118 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009119 NewAttrs.push_back
9120 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009121
9122 ++Idx, ++I;
9123 } while (1);
9124 }
9125
9126 // The trampoline may have been bitcast to a bogus type (FTy).
9127 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009128 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009129
Duncan Sandscdb6d922007-09-17 10:26:40 +00009130 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009131 NewTypes.reserve(FTy->getNumParams()+1);
9132
Duncan Sandscdb6d922007-09-17 10:26:40 +00009133 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009134 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009135 {
9136 unsigned Idx = 1;
9137 FunctionType::param_iterator I = FTy->param_begin(),
9138 E = FTy->param_end();
9139
9140 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009141 if (Idx == NestIdx)
9142 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009143 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009144
9145 if (I == E)
9146 break;
9147
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009148 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009149 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009150
9151 ++Idx, ++I;
9152 } while (1);
9153 }
9154
9155 // Replace the trampoline call with a direct call. Let the generic
9156 // code sort out any function type mismatches.
9157 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009158 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009159 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9160 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009161 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009162
9163 Instruction *NewCaller;
9164 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009165 NewCaller = InvokeInst::Create(NewCallee,
9166 II->getNormalDest(), II->getUnwindDest(),
9167 NewArgs.begin(), NewArgs.end(),
9168 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009169 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009170 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009171 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009172 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9173 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009174 if (cast<CallInst>(Caller)->isTailCall())
9175 cast<CallInst>(NewCaller)->setTailCall();
9176 cast<CallInst>(NewCaller)->
9177 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009178 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009179 }
9180 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9181 Caller->replaceAllUsesWith(NewCaller);
9182 Caller->eraseFromParent();
9183 RemoveFromWorkList(Caller);
9184 return 0;
9185 }
9186 }
9187
9188 // Replace the trampoline call with a direct call. Since there is no 'nest'
9189 // parameter, there is no need to adjust the argument list. Let the generic
9190 // code sort out any function type mismatches.
9191 Constant *NewCallee =
9192 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9193 CS.setCalledFunction(NewCallee);
9194 return CS.getInstruction();
9195}
9196
Chris Lattner7da52b22006-11-01 04:51:18 +00009197/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9198/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9199/// and a single binop.
9200Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9201 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009202 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9203 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009204 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009205 Value *LHSVal = FirstInst->getOperand(0);
9206 Value *RHSVal = FirstInst->getOperand(1);
9207
9208 const Type *LHSType = LHSVal->getType();
9209 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009210
9211 // Scan to see if all operands are the same opcode, all have one use, and all
9212 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009213 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009214 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009215 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009216 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009217 // types or GEP's with different index types.
9218 I->getOperand(0)->getType() != LHSType ||
9219 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009220 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009221
9222 // If they are CmpInst instructions, check their predicates
9223 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9224 if (cast<CmpInst>(I)->getPredicate() !=
9225 cast<CmpInst>(FirstInst)->getPredicate())
9226 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009227
9228 // Keep track of which operand needs a phi node.
9229 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9230 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009231 }
9232
Chris Lattner53738a42006-11-08 19:42:28 +00009233 // Otherwise, this is safe to transform, determine if it is profitable.
9234
9235 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9236 // Indexes are often folded into load/store instructions, so we don't want to
9237 // hide them behind a phi.
9238 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9239 return 0;
9240
Chris Lattner7da52b22006-11-01 04:51:18 +00009241 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009242 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009243 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009244 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009245 NewLHS = PHINode::Create(LHSType,
9246 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009247 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9248 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009249 InsertNewInstBefore(NewLHS, PN);
9250 LHSVal = NewLHS;
9251 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009252
9253 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009254 NewRHS = PHINode::Create(RHSType,
9255 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009256 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9257 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009258 InsertNewInstBefore(NewRHS, PN);
9259 RHSVal = NewRHS;
9260 }
9261
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009262 // Add all operands to the new PHIs.
9263 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9264 if (NewLHS) {
9265 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9266 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9267 }
9268 if (NewRHS) {
9269 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9270 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9271 }
9272 }
9273
Chris Lattner7da52b22006-11-01 04:51:18 +00009274 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009275 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009276 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009277 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009278 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009279 else {
9280 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009281 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009282 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009283}
9284
Chris Lattner76c73142006-11-01 07:13:54 +00009285/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9286/// of the block that defines it. This means that it must be obvious the value
9287/// of the load is not changed from the point of the load to the end of the
9288/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009289///
9290/// Finally, it is safe, but not profitable, to sink a load targetting a
9291/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9292/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009293static bool isSafeToSinkLoad(LoadInst *L) {
9294 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9295
9296 for (++BBI; BBI != E; ++BBI)
9297 if (BBI->mayWriteToMemory())
9298 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009299
9300 // Check for non-address taken alloca. If not address-taken already, it isn't
9301 // profitable to do this xform.
9302 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9303 bool isAddressTaken = false;
9304 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9305 UI != E; ++UI) {
9306 if (isa<LoadInst>(UI)) continue;
9307 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9308 // If storing TO the alloca, then the address isn't taken.
9309 if (SI->getOperand(1) == AI) continue;
9310 }
9311 isAddressTaken = true;
9312 break;
9313 }
9314
9315 if (!isAddressTaken)
9316 return false;
9317 }
9318
Chris Lattner76c73142006-11-01 07:13:54 +00009319 return true;
9320}
9321
Chris Lattner9fe38862003-06-19 17:00:31 +00009322
Chris Lattnerbac32862004-11-14 19:13:23 +00009323// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9324// operator and they all are only used by the PHI, PHI together their
9325// inputs, and do the operation once, to the result of the PHI.
9326Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9327 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9328
9329 // Scan the instruction, looking for input operations that can be folded away.
9330 // If all input operands to the phi are the same instruction (e.g. a cast from
9331 // the same type or "+42") we can pull the operation through the PHI, reducing
9332 // code size and simplifying code.
9333 Constant *ConstantOp = 0;
9334 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009335 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009336 if (isa<CastInst>(FirstInst)) {
9337 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009338 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009339 // Can fold binop, compare or shift here if the RHS is a constant,
9340 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009341 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009342 if (ConstantOp == 0)
9343 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009344 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9345 isVolatile = LI->isVolatile();
9346 // We can't sink the load if the loaded value could be modified between the
9347 // load and the PHI.
9348 if (LI->getParent() != PN.getIncomingBlock(0) ||
9349 !isSafeToSinkLoad(LI))
9350 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009351 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009352 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009353 return FoldPHIArgBinOpIntoPHI(PN);
9354 // Can't handle general GEPs yet.
9355 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009356 } else {
9357 return 0; // Cannot fold this operation.
9358 }
9359
9360 // Check to see if all arguments are the same operation.
9361 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9362 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9363 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009364 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009365 return 0;
9366 if (CastSrcTy) {
9367 if (I->getOperand(0)->getType() != CastSrcTy)
9368 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009369 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009370 // We can't sink the load if the loaded value could be modified between
9371 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009372 if (LI->isVolatile() != isVolatile ||
9373 LI->getParent() != PN.getIncomingBlock(i) ||
9374 !isSafeToSinkLoad(LI))
9375 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009376
9377 // If the PHI is volatile and its block has multiple successors, sinking
9378 // it would remove a load of the volatile value from the path through the
9379 // other successor.
9380 if (isVolatile &&
9381 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9382 return 0;
9383
9384
Chris Lattnerbac32862004-11-14 19:13:23 +00009385 } else if (I->getOperand(1) != ConstantOp) {
9386 return 0;
9387 }
9388 }
9389
9390 // Okay, they are all the same operation. Create a new PHI node of the
9391 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009392 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9393 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009394 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009395
9396 Value *InVal = FirstInst->getOperand(0);
9397 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009398
9399 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009400 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9401 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9402 if (NewInVal != InVal)
9403 InVal = 0;
9404 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9405 }
9406
9407 Value *PhiVal;
9408 if (InVal) {
9409 // The new PHI unions all of the same values together. This is really
9410 // common, so we handle it intelligently here for compile-time speed.
9411 PhiVal = InVal;
9412 delete NewPN;
9413 } else {
9414 InsertNewInstBefore(NewPN, PN);
9415 PhiVal = NewPN;
9416 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009417
Chris Lattnerbac32862004-11-14 19:13:23 +00009418 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009419 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009420 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009421 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009422 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009423 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009424 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009425 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009426 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9427
9428 // If this was a volatile load that we are merging, make sure to loop through
9429 // and mark all the input loads as non-volatile. If we don't do this, we will
9430 // insert a new volatile load and the old ones will not be deletable.
9431 if (isVolatile)
9432 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9433 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9434
9435 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009436}
Chris Lattnera1be5662002-05-02 17:06:02 +00009437
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009438/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9439/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009440static bool DeadPHICycle(PHINode *PN,
9441 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009442 if (PN->use_empty()) return true;
9443 if (!PN->hasOneUse()) return false;
9444
9445 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009446 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009447 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009448
9449 // Don't scan crazily complex things.
9450 if (PotentiallyDeadPHIs.size() == 16)
9451 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009452
9453 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9454 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009455
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009456 return false;
9457}
9458
Chris Lattnercf5008a2007-11-06 21:52:06 +00009459/// PHIsEqualValue - Return true if this phi node is always equal to
9460/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9461/// z = some value; x = phi (y, z); y = phi (x, z)
9462static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9463 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9464 // See if we already saw this PHI node.
9465 if (!ValueEqualPHIs.insert(PN))
9466 return true;
9467
9468 // Don't scan crazily complex things.
9469 if (ValueEqualPHIs.size() == 16)
9470 return false;
9471
9472 // Scan the operands to see if they are either phi nodes or are equal to
9473 // the value.
9474 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9475 Value *Op = PN->getIncomingValue(i);
9476 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9477 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9478 return false;
9479 } else if (Op != NonPhiInVal)
9480 return false;
9481 }
9482
9483 return true;
9484}
9485
9486
Chris Lattner473945d2002-05-06 18:06:38 +00009487// PHINode simplification
9488//
Chris Lattner7e708292002-06-25 16:13:24 +00009489Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009490 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009491 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009492
Owen Anderson7e057142006-07-10 22:03:18 +00009493 if (Value *V = PN.hasConstantValue())
9494 return ReplaceInstUsesWith(PN, V);
9495
Owen Anderson7e057142006-07-10 22:03:18 +00009496 // If all PHI operands are the same operation, pull them through the PHI,
9497 // reducing code size.
9498 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9499 PN.getIncomingValue(0)->hasOneUse())
9500 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9501 return Result;
9502
9503 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9504 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9505 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009506 if (PN.hasOneUse()) {
9507 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9508 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009509 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009510 PotentiallyDeadPHIs.insert(&PN);
9511 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9512 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9513 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009514
9515 // If this phi has a single use, and if that use just computes a value for
9516 // the next iteration of a loop, delete the phi. This occurs with unused
9517 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9518 // common case here is good because the only other things that catch this
9519 // are induction variable analysis (sometimes) and ADCE, which is only run
9520 // late.
9521 if (PHIUser->hasOneUse() &&
9522 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9523 PHIUser->use_back() == &PN) {
9524 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9525 }
9526 }
Owen Anderson7e057142006-07-10 22:03:18 +00009527
Chris Lattnercf5008a2007-11-06 21:52:06 +00009528 // We sometimes end up with phi cycles that non-obviously end up being the
9529 // same value, for example:
9530 // z = some value; x = phi (y, z); y = phi (x, z)
9531 // where the phi nodes don't necessarily need to be in the same block. Do a
9532 // quick check to see if the PHI node only contains a single non-phi value, if
9533 // so, scan to see if the phi cycle is actually equal to that value.
9534 {
9535 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9536 // Scan for the first non-phi operand.
9537 while (InValNo != NumOperandVals &&
9538 isa<PHINode>(PN.getIncomingValue(InValNo)))
9539 ++InValNo;
9540
9541 if (InValNo != NumOperandVals) {
9542 Value *NonPhiInVal = PN.getOperand(InValNo);
9543
9544 // Scan the rest of the operands to see if there are any conflicts, if so
9545 // there is no need to recursively scan other phis.
9546 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9547 Value *OpVal = PN.getIncomingValue(InValNo);
9548 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9549 break;
9550 }
9551
9552 // If we scanned over all operands, then we have one unique value plus
9553 // phi values. Scan PHI nodes to see if they all merge in each other or
9554 // the value.
9555 if (InValNo == NumOperandVals) {
9556 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9557 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9558 return ReplaceInstUsesWith(PN, NonPhiInVal);
9559 }
9560 }
9561 }
Chris Lattner60921c92003-12-19 05:58:40 +00009562 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009563}
9564
Reid Spencer17212df2006-12-12 09:18:51 +00009565static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9566 Instruction *InsertPoint,
9567 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009568 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9569 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009570 // We must cast correctly to the pointer type. Ensure that we
9571 // sign extend the integer value if it is smaller as this is
9572 // used for address computation.
9573 Instruction::CastOps opcode =
9574 (VTySize < PtrSize ? Instruction::SExt :
9575 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9576 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009577}
9578
Chris Lattnera1be5662002-05-02 17:06:02 +00009579
Chris Lattner7e708292002-06-25 16:13:24 +00009580Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009581 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009582 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009583 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009584 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009585 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009586
Chris Lattnere87597f2004-10-16 18:11:37 +00009587 if (isa<UndefValue>(GEP.getOperand(0)))
9588 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9589
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009590 bool HasZeroPointerIndex = false;
9591 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9592 HasZeroPointerIndex = C->isNullValue();
9593
9594 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009595 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009596
Chris Lattner28977af2004-04-05 01:30:19 +00009597 // Eliminate unneeded casts for indices.
9598 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009599
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009600 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009601 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9602 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009603 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009604 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009605 if (CI->getOpcode() == Instruction::ZExt ||
9606 CI->getOpcode() == Instruction::SExt) {
9607 const Type *SrcTy = CI->getOperand(0)->getType();
9608 // We can eliminate a cast from i32 to i64 iff the target
9609 // is a 32-bit pointer target.
9610 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9611 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +00009612 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +00009613 }
9614 }
9615 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009616 // If we are using a wider index than needed for this platform, shrink it
9617 // to what we need. If the incoming value needs a cast instruction,
9618 // insert it. This explicit cast can make subsequent optimizations more
9619 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +00009620 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009621 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009622 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +00009623 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +00009624 MadeChange = true;
9625 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009626 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9627 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +00009628 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009629 MadeChange = true;
9630 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009631 }
Chris Lattner28977af2004-04-05 01:30:19 +00009632 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009633 }
Chris Lattner28977af2004-04-05 01:30:19 +00009634 if (MadeChange) return &GEP;
9635
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009636 // If this GEP instruction doesn't move the pointer, and if the input operand
9637 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9638 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009639 if (GEP.hasAllZeroIndices()) {
9640 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9641 // If the bitcast is of an allocation, and the allocation will be
9642 // converted to match the type of the cast, don't touch this.
9643 if (isa<AllocationInst>(BCI->getOperand(0))) {
9644 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009645 if (Instruction *I = visitBitCast(*BCI)) {
9646 if (I != BCI) {
9647 I->takeName(BCI);
9648 BCI->getParent()->getInstList().insert(BCI, I);
9649 ReplaceInstUsesWith(*BCI, I);
9650 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009651 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009652 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009653 }
9654 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9655 }
9656 }
9657
Chris Lattner90ac28c2002-08-02 19:29:35 +00009658 // Combine Indices - If the source pointer to this getelementptr instruction
9659 // is a getelementptr instruction, combine the indices of the two
9660 // getelementptr instructions into a single instruction.
9661 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009662 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009663 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009664 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009665
9666 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009667 // Note that if our source is a gep chain itself that we wait for that
9668 // chain to be resolved before we perform this transformation. This
9669 // avoids us creating a TON of code in some cases.
9670 //
9671 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9672 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9673 return 0; // Wait until our source is folded to completion.
9674
Chris Lattner72588fc2007-02-15 22:48:32 +00009675 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009676
9677 // Find out whether the last index in the source GEP is a sequential idx.
9678 bool EndsWithSequential = false;
9679 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9680 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009681 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009682
Chris Lattner90ac28c2002-08-02 19:29:35 +00009683 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009684 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009685 // Replace: gep (gep %P, long B), long A, ...
9686 // With: T = long A+B; gep %P, T, ...
9687 //
Chris Lattner620ce142004-05-07 22:09:22 +00009688 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009689 if (SO1 == Constant::getNullValue(SO1->getType())) {
9690 Sum = GO1;
9691 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9692 Sum = SO1;
9693 } else {
9694 // If they aren't the same type, convert both to an integer of the
9695 // target's pointer size.
9696 if (SO1->getType() != GO1->getType()) {
9697 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009698 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009699 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009700 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009701 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009702 unsigned PS = TD->getPointerSizeInBits();
9703 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009704 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009705 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009706
Duncan Sands514ab342007-11-01 20:53:16 +00009707 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009708 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009709 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009710 } else {
9711 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009712 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9713 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009714 }
9715 }
9716 }
Chris Lattner620ce142004-05-07 22:09:22 +00009717 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9718 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9719 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009720 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +00009721 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009722 }
Chris Lattner28977af2004-04-05 01:30:19 +00009723 }
Chris Lattner620ce142004-05-07 22:09:22 +00009724
9725 // Recycle the GEP we already have if possible.
9726 if (SrcGEPOperands.size() == 2) {
9727 GEP.setOperand(0, SrcGEPOperands[0]);
9728 GEP.setOperand(1, Sum);
9729 return &GEP;
9730 } else {
9731 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9732 SrcGEPOperands.end()-1);
9733 Indices.push_back(Sum);
9734 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9735 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009736 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009737 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009738 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009739 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009740 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9741 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009742 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9743 }
9744
9745 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009746 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9747 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009748
Chris Lattner620ce142004-05-07 22:09:22 +00009749 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009750 // GEP of global variable. If all of the indices for this GEP are
9751 // constants, we can promote this to a constexpr instead of an instruction.
9752
9753 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009754 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009755 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9756 for (; I != E && isa<Constant>(*I); ++I)
9757 Indices.push_back(cast<Constant>(*I));
9758
9759 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009760 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9761 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009762
9763 // Replace all uses of the GEP with the new constexpr...
9764 return ReplaceInstUsesWith(GEP, CE);
9765 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009766 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009767 if (!isa<PointerType>(X->getType())) {
9768 // Not interesting. Source pointer must be a cast from pointer.
9769 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009770 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9771 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009772 //
9773 // This occurs when the program declares an array extern like "int X[];"
9774 //
9775 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9776 const PointerType *XTy = cast<PointerType>(X->getType());
9777 if (const ArrayType *XATy =
9778 dyn_cast<ArrayType>(XTy->getElementType()))
9779 if (const ArrayType *CATy =
9780 dyn_cast<ArrayType>(CPTy->getElementType()))
9781 if (CATy->getElementType() == XATy->getElementType()) {
9782 // At this point, we know that the cast source type is a pointer
9783 // to an array of the same type as the destination pointer
9784 // array. Because the array type is never stepped over (there
9785 // is a leading zero) we can fold the cast into this GEP.
9786 GEP.setOperand(0, X);
9787 return &GEP;
9788 }
9789 } else if (GEP.getNumOperands() == 2) {
9790 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009791 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9792 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009793 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9794 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9795 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009796 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9797 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009798 Value *Idx[2];
9799 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9800 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009801 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009802 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009803 // V and GEP are both pointer types --> BitCast
9804 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009805 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009806
9807 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009808 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009809 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009810 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009811
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009812 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009813 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009814 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009815
9816 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9817 // allow either a mul, shift, or constant here.
9818 Value *NewIdx = 0;
9819 ConstantInt *Scale = 0;
9820 if (ArrayEltSize == 1) {
9821 NewIdx = GEP.getOperand(1);
9822 Scale = ConstantInt::get(NewIdx->getType(), 1);
9823 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009824 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009825 Scale = CI;
9826 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9827 if (Inst->getOpcode() == Instruction::Shl &&
9828 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009829 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9830 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9831 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009832 NewIdx = Inst->getOperand(0);
9833 } else if (Inst->getOpcode() == Instruction::Mul &&
9834 isa<ConstantInt>(Inst->getOperand(1))) {
9835 Scale = cast<ConstantInt>(Inst->getOperand(1));
9836 NewIdx = Inst->getOperand(0);
9837 }
9838 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009839
Chris Lattner7835cdd2005-09-13 18:36:04 +00009840 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009841 // out, perform the transformation. Note, we don't know whether Scale is
9842 // signed or not. We'll use unsigned version of division/modulo
9843 // operation after making sure Scale doesn't have the sign bit set.
9844 if (Scale && Scale->getSExtValue() >= 0LL &&
9845 Scale->getZExtValue() % ArrayEltSize == 0) {
9846 Scale = ConstantInt::get(Scale->getType(),
9847 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009848 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009849 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009850 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009851 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00009852 NewIdx = InsertNewInstBefore(Sc, GEP);
9853 }
9854
9855 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009856 Value *Idx[2];
9857 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9858 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009859 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009860 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009861 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9862 // The NewGEP must be pointer typed, so must the old one -> BitCast
9863 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009864 }
9865 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009866 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009867 }
9868
Chris Lattner8a2a3112001-12-14 16:52:21 +00009869 return 0;
9870}
9871
Chris Lattner0864acf2002-11-04 16:18:53 +00009872Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9873 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009874 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009875 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9876 const Type *NewTy =
9877 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009878 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009879
9880 // Create and insert the replacement instruction...
9881 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009882 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009883 else {
9884 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009885 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009886 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009887
9888 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009889
Chris Lattner0864acf2002-11-04 16:18:53 +00009890 // Scan to the end of the allocation instructions, to skip over a block of
9891 // allocas if possible...
9892 //
9893 BasicBlock::iterator It = New;
9894 while (isa<AllocationInst>(*It)) ++It;
9895
9896 // Now that I is pointing to the first non-allocation-inst in the block,
9897 // insert our getelementptr instruction...
9898 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009899 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009900 Value *Idx[2];
9901 Idx[0] = NullIdx;
9902 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +00009903 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9904 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009905
9906 // Now make everything use the getelementptr instead of the original
9907 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009908 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009909 } else if (isa<UndefValue>(AI.getArraySize())) {
9910 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009911 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009912 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009913
9914 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9915 // Note that we only do this for alloca's, because malloc should allocate and
9916 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009917 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009918 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009919 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9920
Chris Lattner0864acf2002-11-04 16:18:53 +00009921 return 0;
9922}
9923
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009924Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9925 Value *Op = FI.getOperand(0);
9926
Chris Lattner17be6352004-10-18 02:59:09 +00009927 // free undef -> unreachable.
9928 if (isa<UndefValue>(Op)) {
9929 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009930 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009931 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009932 return EraseInstFromFunction(FI);
9933 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009934
Chris Lattner6160e852004-02-28 04:57:37 +00009935 // If we have 'free null' delete the instruction. This can happen in stl code
9936 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009937 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009938 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009939
9940 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9941 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9942 FI.setOperand(0, CI->getOperand(0));
9943 return &FI;
9944 }
9945
9946 // Change free (gep X, 0,0,0,0) into free(X)
9947 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9948 if (GEPI->hasAllZeroIndices()) {
9949 AddToWorkList(GEPI);
9950 FI.setOperand(0, GEPI->getOperand(0));
9951 return &FI;
9952 }
9953 }
9954
9955 // Change free(malloc) into nothing, if the malloc has a single use.
9956 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9957 if (MI->hasOneUse()) {
9958 EraseInstFromFunction(FI);
9959 return EraseInstFromFunction(*MI);
9960 }
Chris Lattner6160e852004-02-28 04:57:37 +00009961
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009962 return 0;
9963}
9964
9965
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009966/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009967static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009968 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009969 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009970 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009971
Devang Patel99db6ad2007-10-18 19:52:32 +00009972 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9973 // Instead of loading constant c string, use corresponding integer value
9974 // directly if string length is small enough.
9975 const std::string &Str = CE->getOperand(0)->getStringValue();
9976 if (!Str.empty()) {
9977 unsigned len = Str.length();
9978 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9979 unsigned numBits = Ty->getPrimitiveSizeInBits();
9980 // Replace LI with immediate integer store.
9981 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009982 APInt StrVal(numBits, 0);
9983 APInt SingleChar(numBits, 0);
9984 if (TD->isLittleEndian()) {
9985 for (signed i = len-1; i >= 0; i--) {
9986 SingleChar = (uint64_t) Str[i];
9987 StrVal = (StrVal << 8) | SingleChar;
9988 }
9989 } else {
9990 for (unsigned i = 0; i < len; i++) {
9991 SingleChar = (uint64_t) Str[i];
9992 StrVal = (StrVal << 8) | SingleChar;
9993 }
9994 // Append NULL at the end.
9995 SingleChar = 0;
9996 StrVal = (StrVal << 8) | SingleChar;
9997 }
9998 Value *NL = ConstantInt::get(StrVal);
9999 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010000 }
10001 }
10002 }
10003
Chris Lattnerb89e0712004-07-13 01:49:43 +000010004 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010005 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010006 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010007
Reid Spencer42230162007-01-22 05:51:25 +000010008 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010009 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010010 // If the source is an array, the code below will not succeed. Check to
10011 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10012 // constants.
10013 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10014 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10015 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010016 Value *Idxs[2];
10017 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10018 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010019 SrcTy = cast<PointerType>(CastOp->getType());
10020 SrcPTy = SrcTy->getElementType();
10021 }
10022
Reid Spencer42230162007-01-22 05:51:25 +000010023 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010024 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010025 // Do not allow turning this into a load of an integer, which is then
10026 // casted to a pointer, this pessimizes pointer analysis a lot.
10027 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010028 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10029 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010030
Chris Lattnerf9527852005-01-31 04:50:46 +000010031 // Okay, we are casting from one integer or pointer type to another of
10032 // the same size. Instead of casting the pointer before the load, cast
10033 // the result of the loaded value.
10034 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10035 CI->getName(),
10036 LI.isVolatile()),LI);
10037 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010038 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010039 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010040 }
10041 }
10042 return 0;
10043}
10044
Chris Lattnerc10aced2004-09-19 18:43:46 +000010045/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010046/// from this value cannot trap. If it is not obviously safe to load from the
10047/// specified pointer, we do a quick local scan of the basic block containing
10048/// ScanFrom, to determine if the address is already accessed.
10049static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010050 // If it is an alloca it is always safe to load from.
10051 if (isa<AllocaInst>(V)) return true;
10052
Duncan Sands46318cd2007-09-19 10:25:38 +000010053 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010054 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010055 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010056 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010057
10058 // Otherwise, be a little bit agressive by scanning the local block where we
10059 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010060 // from/to. If so, the previous load or store would have already trapped,
10061 // so there is no harm doing an extra load (also, CSE will later eliminate
10062 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010063 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10064
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010065 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010066 --BBI;
10067
10068 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10069 if (LI->getOperand(0) == V) return true;
10070 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10071 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010072
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010073 }
Chris Lattner8a375202004-09-19 19:18:10 +000010074 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010075}
10076
Chris Lattner8d2e8882007-08-11 18:48:48 +000010077/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10078/// until we find the underlying object a pointer is referring to or something
10079/// we don't understand. Note that the returned pointer may be offset from the
10080/// input, because we ignore GEP indices.
10081static Value *GetUnderlyingObject(Value *Ptr) {
10082 while (1) {
10083 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10084 if (CE->getOpcode() == Instruction::BitCast ||
10085 CE->getOpcode() == Instruction::GetElementPtr)
10086 Ptr = CE->getOperand(0);
10087 else
10088 return Ptr;
10089 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10090 Ptr = BCI->getOperand(0);
10091 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10092 Ptr = GEP->getOperand(0);
10093 } else {
10094 return Ptr;
10095 }
10096 }
10097}
10098
Chris Lattner833b8a42003-06-26 05:06:25 +000010099Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10100 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010101
Dan Gohman9941f742007-07-20 16:34:21 +000010102 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010103 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10104 if (KnownAlign >
10105 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10106 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010107 LI.setAlignment(KnownAlign);
10108
Chris Lattner37366c12005-05-01 04:24:53 +000010109 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010110 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010111 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010112 return Res;
10113
10114 // None of the following transforms are legal for volatile loads.
10115 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010116
Chris Lattner62f254d2005-09-12 22:00:15 +000010117 if (&LI.getParent()->front() != &LI) {
10118 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010119 // If the instruction immediately before this is a store to the same
10120 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010121 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10122 if (SI->getOperand(1) == LI.getOperand(0))
10123 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010124 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10125 if (LIB->getOperand(0) == LI.getOperand(0))
10126 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010127 }
Chris Lattner37366c12005-05-01 04:24:53 +000010128
Christopher Lambb15147e2007-12-29 07:56:53 +000010129 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10130 const Value *GEPI0 = GEPI->getOperand(0);
10131 // TODO: Consider a target hook for valid address spaces for this xform.
10132 if (isa<ConstantPointerNull>(GEPI0) &&
10133 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010134 // Insert a new store to null instruction before the load to indicate
10135 // that this code is not reachable. We do this instead of inserting
10136 // an unreachable instruction directly because we cannot modify the
10137 // CFG.
10138 new StoreInst(UndefValue::get(LI.getType()),
10139 Constant::getNullValue(Op->getType()), &LI);
10140 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10141 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010142 }
Chris Lattner37366c12005-05-01 04:24:53 +000010143
Chris Lattnere87597f2004-10-16 18:11:37 +000010144 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010145 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010146 // TODO: Consider a target hook for valid address spaces for this xform.
10147 if (isa<UndefValue>(C) || (C->isNullValue() &&
10148 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010149 // Insert a new store to null instruction before the load to indicate that
10150 // this code is not reachable. We do this instead of inserting an
10151 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010152 new StoreInst(UndefValue::get(LI.getType()),
10153 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010154 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010155 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010156
Chris Lattnere87597f2004-10-16 18:11:37 +000010157 // Instcombine load (constant global) into the value loaded.
10158 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010159 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010160 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010161
Chris Lattnere87597f2004-10-16 18:11:37 +000010162 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010163 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010164 if (CE->getOpcode() == Instruction::GetElementPtr) {
10165 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010166 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010167 if (Constant *V =
10168 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010169 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010170 if (CE->getOperand(0)->isNullValue()) {
10171 // Insert a new store to null instruction before the load to indicate
10172 // that this code is not reachable. We do this instead of inserting
10173 // an unreachable instruction directly because we cannot modify the
10174 // CFG.
10175 new StoreInst(UndefValue::get(LI.getType()),
10176 Constant::getNullValue(Op->getType()), &LI);
10177 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10178 }
10179
Reid Spencer3da59db2006-11-27 01:05:10 +000010180 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010181 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010182 return Res;
10183 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010184 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010185 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010186
10187 // If this load comes from anywhere in a constant global, and if the global
10188 // is all undef or zero, we know what it loads.
10189 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10190 if (GV->isConstant() && GV->hasInitializer()) {
10191 if (GV->getInitializer()->isNullValue())
10192 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10193 else if (isa<UndefValue>(GV->getInitializer()))
10194 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10195 }
10196 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010197
Chris Lattner37366c12005-05-01 04:24:53 +000010198 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010199 // Change select and PHI nodes to select values instead of addresses: this
10200 // helps alias analysis out a lot, allows many others simplifications, and
10201 // exposes redundancy in the code.
10202 //
10203 // Note that we cannot do the transformation unless we know that the
10204 // introduced loads cannot trap! Something like this is valid as long as
10205 // the condition is always false: load (select bool %C, int* null, int* %G),
10206 // but it would not be valid if we transformed it to load from null
10207 // unconditionally.
10208 //
10209 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10210 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010211 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10212 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010213 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010214 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010215 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010216 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010217 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010218 }
10219
Chris Lattner684fe212004-09-23 15:46:00 +000010220 // load (select (cond, null, P)) -> load P
10221 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10222 if (C->isNullValue()) {
10223 LI.setOperand(0, SI->getOperand(2));
10224 return &LI;
10225 }
10226
10227 // load (select (cond, P, null)) -> load P
10228 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10229 if (C->isNullValue()) {
10230 LI.setOperand(0, SI->getOperand(1));
10231 return &LI;
10232 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010233 }
10234 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010235 return 0;
10236}
10237
Reid Spencer55af2b52007-01-19 21:20:31 +000010238/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010239/// when possible.
10240static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10241 User *CI = cast<User>(SI.getOperand(1));
10242 Value *CastOp = CI->getOperand(0);
10243
10244 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10245 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10246 const Type *SrcPTy = SrcTy->getElementType();
10247
Reid Spencer42230162007-01-22 05:51:25 +000010248 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010249 // If the source is an array, the code below will not succeed. Check to
10250 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10251 // constants.
10252 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10253 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10254 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010255 Value* Idxs[2];
10256 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10257 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010258 SrcTy = cast<PointerType>(CastOp->getType());
10259 SrcPTy = SrcTy->getElementType();
10260 }
10261
Reid Spencer67f827c2007-01-20 23:35:48 +000010262 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10263 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10264 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010265
10266 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010267 // the same size. Instead of casting the pointer before
10268 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010269 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010270 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010271 Instruction::CastOps opcode = Instruction::BitCast;
10272 const Type* CastSrcTy = SIOp0->getType();
10273 const Type* CastDstTy = SrcPTy;
10274 if (isa<PointerType>(CastDstTy)) {
10275 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010276 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010277 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010278 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010279 opcode = Instruction::PtrToInt;
10280 }
10281 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010282 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010283 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010284 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010285 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010286 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010287 return new StoreInst(NewCast, CastOp);
10288 }
10289 }
10290 }
10291 return 0;
10292}
10293
Chris Lattner2f503e62005-01-31 05:36:43 +000010294Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10295 Value *Val = SI.getOperand(0);
10296 Value *Ptr = SI.getOperand(1);
10297
10298 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010299 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010300 ++NumCombined;
10301 return 0;
10302 }
Chris Lattner836692d2007-01-15 06:51:56 +000010303
10304 // If the RHS is an alloca with a single use, zapify the store, making the
10305 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010306 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010307 if (isa<AllocaInst>(Ptr)) {
10308 EraseInstFromFunction(SI);
10309 ++NumCombined;
10310 return 0;
10311 }
10312
10313 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10314 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10315 GEP->getOperand(0)->hasOneUse()) {
10316 EraseInstFromFunction(SI);
10317 ++NumCombined;
10318 return 0;
10319 }
10320 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010321
Dan Gohman9941f742007-07-20 16:34:21 +000010322 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010323 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10324 if (KnownAlign >
10325 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10326 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010327 SI.setAlignment(KnownAlign);
10328
Chris Lattner9ca96412006-02-08 03:25:32 +000010329 // Do really simple DSE, to catch cases where there are several consequtive
10330 // stores to the same location, separated by a few arithmetic operations. This
10331 // situation often occurs with bitfield accesses.
10332 BasicBlock::iterator BBI = &SI;
10333 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10334 --ScanInsts) {
10335 --BBI;
10336
10337 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10338 // Prev store isn't volatile, and stores to the same location?
10339 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10340 ++NumDeadStore;
10341 ++BBI;
10342 EraseInstFromFunction(*PrevSI);
10343 continue;
10344 }
10345 break;
10346 }
10347
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010348 // If this is a load, we have to stop. However, if the loaded value is from
10349 // the pointer we're loading and is producing the pointer we're storing,
10350 // then *this* store is dead (X = load P; store X -> P).
10351 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010352 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010353 EraseInstFromFunction(SI);
10354 ++NumCombined;
10355 return 0;
10356 }
10357 // Otherwise, this is a load from some other location. Stores before it
10358 // may not be dead.
10359 break;
10360 }
10361
Chris Lattner9ca96412006-02-08 03:25:32 +000010362 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010363 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010364 break;
10365 }
10366
10367
10368 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010369
10370 // store X, null -> turns into 'unreachable' in SimplifyCFG
10371 if (isa<ConstantPointerNull>(Ptr)) {
10372 if (!isa<UndefValue>(Val)) {
10373 SI.setOperand(0, UndefValue::get(Val->getType()));
10374 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010375 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010376 ++NumCombined;
10377 }
10378 return 0; // Do not modify these!
10379 }
10380
10381 // store undef, Ptr -> noop
10382 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010383 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010384 ++NumCombined;
10385 return 0;
10386 }
10387
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010388 // If the pointer destination is a cast, see if we can fold the cast into the
10389 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010390 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010391 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10392 return Res;
10393 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010394 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010395 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10396 return Res;
10397
Chris Lattner408902b2005-09-12 23:23:25 +000010398
10399 // If this store is the last instruction in the basic block, and if the block
10400 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010401 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010402 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010403 if (BI->isUnconditional())
10404 if (SimplifyStoreAtEndOfBlock(SI))
10405 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010406
Chris Lattner2f503e62005-01-31 05:36:43 +000010407 return 0;
10408}
10409
Chris Lattner3284d1f2007-04-15 00:07:55 +000010410/// SimplifyStoreAtEndOfBlock - Turn things like:
10411/// if () { *P = v1; } else { *P = v2 }
10412/// into a phi node with a store in the successor.
10413///
Chris Lattner31755a02007-04-15 01:02:18 +000010414/// Simplify things like:
10415/// *P = v1; if () { *P = v2; }
10416/// into a phi node with a store in the successor.
10417///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010418bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10419 BasicBlock *StoreBB = SI.getParent();
10420
10421 // Check to see if the successor block has exactly two incoming edges. If
10422 // so, see if the other predecessor contains a store to the same location.
10423 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010424 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010425
10426 // Determine whether Dest has exactly two predecessors and, if so, compute
10427 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010428 pred_iterator PI = pred_begin(DestBB);
10429 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010430 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010431 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010432 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010433 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010434 return false;
10435
10436 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010437 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010438 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010439 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010440 }
Chris Lattner31755a02007-04-15 01:02:18 +000010441 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010442 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000010443
10444 // Bail out if all the relevant blocks aren't distinct (this can happen,
10445 // for example, if SI is in an infinite loop)
10446 if (StoreBB == DestBB || OtherBB == DestBB)
10447 return false;
10448
Chris Lattner31755a02007-04-15 01:02:18 +000010449 // Verify that the other block ends in a branch and is not otherwise empty.
10450 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010451 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010452 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010453 return false;
10454
Chris Lattner31755a02007-04-15 01:02:18 +000010455 // If the other block ends in an unconditional branch, check for the 'if then
10456 // else' case. there is an instruction before the branch.
10457 StoreInst *OtherStore = 0;
10458 if (OtherBr->isUnconditional()) {
10459 // If this isn't a store, or isn't a store to the same location, bail out.
10460 --BBI;
10461 OtherStore = dyn_cast<StoreInst>(BBI);
10462 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10463 return false;
10464 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010465 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010466 // destinations is StoreBB, then we have the if/then case.
10467 if (OtherBr->getSuccessor(0) != StoreBB &&
10468 OtherBr->getSuccessor(1) != StoreBB)
10469 return false;
10470
10471 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010472 // if/then triangle. See if there is a store to the same ptr as SI that
10473 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010474 for (;; --BBI) {
10475 // Check to see if we find the matching store.
10476 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10477 if (OtherStore->getOperand(1) != SI.getOperand(1))
10478 return false;
10479 break;
10480 }
Eli Friedman6903a242008-06-13 22:02:12 +000010481 // If we find something that may be using or overwriting the stored
10482 // value, or if we run out of instructions, we can't do the xform.
10483 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000010484 BBI == OtherBB->begin())
10485 return false;
10486 }
10487
10488 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000010489 // make sure nothing reads or overwrites the stored value in
10490 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010491 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10492 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000010493 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000010494 return false;
10495 }
10496 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010497
Chris Lattner31755a02007-04-15 01:02:18 +000010498 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010499 Value *MergedVal = OtherStore->getOperand(0);
10500 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010501 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010502 PN->reserveOperandSpace(2);
10503 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010504 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10505 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010506 }
10507
10508 // Advance to a place where it is safe to insert the new store and
10509 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000010510 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010511 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10512 OtherStore->isVolatile()), *BBI);
10513
10514 // Nuke the old stores.
10515 EraseInstFromFunction(SI);
10516 EraseInstFromFunction(*OtherStore);
10517 ++NumCombined;
10518 return true;
10519}
10520
Chris Lattner2f503e62005-01-31 05:36:43 +000010521
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010522Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10523 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010524 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010525 BasicBlock *TrueDest;
10526 BasicBlock *FalseDest;
10527 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10528 !isa<Constant>(X)) {
10529 // Swap Destinations and condition...
10530 BI.setCondition(X);
10531 BI.setSuccessor(0, FalseDest);
10532 BI.setSuccessor(1, TrueDest);
10533 return &BI;
10534 }
10535
Reid Spencere4d87aa2006-12-23 06:05:41 +000010536 // Cannonicalize fcmp_one -> fcmp_oeq
10537 FCmpInst::Predicate FPred; Value *Y;
10538 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10539 TrueDest, FalseDest)))
10540 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10541 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10542 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010543 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010544 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10545 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010546 // Swap Destinations and condition...
10547 BI.setCondition(NewSCC);
10548 BI.setSuccessor(0, FalseDest);
10549 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010550 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010551 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010552 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010553 return &BI;
10554 }
10555
10556 // Cannonicalize icmp_ne -> icmp_eq
10557 ICmpInst::Predicate IPred;
10558 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10559 TrueDest, FalseDest)))
10560 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10561 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10562 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10563 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010564 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010565 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10566 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010567 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010568 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010569 BI.setSuccessor(0, FalseDest);
10570 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010571 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010572 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010573 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010574 return &BI;
10575 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010576
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010577 return 0;
10578}
Chris Lattner0864acf2002-11-04 16:18:53 +000010579
Chris Lattner46238a62004-07-03 00:26:11 +000010580Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10581 Value *Cond = SI.getCondition();
10582 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10583 if (I->getOpcode() == Instruction::Add)
10584 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10585 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10586 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010587 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010588 AddRHS));
10589 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010590 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010591 return &SI;
10592 }
10593 }
10594 return 0;
10595}
10596
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010597Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10598 // See if we are trying to extract a known value. If so, use that instead.
Matthijs Kooijman710eb232008-06-16 12:57:37 +000010599 if (Value *Elt = FindInsertedValue(EV.getOperand(0), EV.idx_begin(),
Matthijs Kooijman0a7413d2008-06-16 13:13:08 +000010600 EV.idx_end(), &EV))
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000010601 return ReplaceInstUsesWith(EV, Elt);
10602
10603 // No changes
10604 return 0;
10605}
10606
Chris Lattner220b0cf2006-03-05 00:22:33 +000010607/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10608/// is to leave as a vector operation.
10609static bool CheapToScalarize(Value *V, bool isConstant) {
10610 if (isa<ConstantAggregateZero>(V))
10611 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010612 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010613 if (isConstant) return true;
10614 // If all elts are the same, we can extract.
10615 Constant *Op0 = C->getOperand(0);
10616 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10617 if (C->getOperand(i) != Op0)
10618 return false;
10619 return true;
10620 }
10621 Instruction *I = dyn_cast<Instruction>(V);
10622 if (!I) return false;
10623
10624 // Insert element gets simplified to the inserted element or is deleted if
10625 // this is constant idx extract element and its a constant idx insertelt.
10626 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10627 isa<ConstantInt>(I->getOperand(2)))
10628 return true;
10629 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10630 return true;
10631 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10632 if (BO->hasOneUse() &&
10633 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10634 CheapToScalarize(BO->getOperand(1), isConstant)))
10635 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010636 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10637 if (CI->hasOneUse() &&
10638 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10639 CheapToScalarize(CI->getOperand(1), isConstant)))
10640 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010641
10642 return false;
10643}
10644
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010645/// Read and decode a shufflevector mask.
10646///
10647/// It turns undef elements into values that are larger than the number of
10648/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010649static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10650 unsigned NElts = SVI->getType()->getNumElements();
10651 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10652 return std::vector<unsigned>(NElts, 0);
10653 if (isa<UndefValue>(SVI->getOperand(2)))
10654 return std::vector<unsigned>(NElts, 2*NElts);
10655
10656 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010657 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000010658 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10659 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000010660 Result.push_back(NElts*2); // undef -> 8
10661 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000010662 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010663 return Result;
10664}
10665
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010666/// FindScalarElement - Given a vector and an element number, see if the scalar
10667/// value is already around as a register, for example if it were inserted then
10668/// extracted from the vector.
10669static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010670 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10671 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010672 unsigned Width = PTy->getNumElements();
10673 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010674 return UndefValue::get(PTy->getElementType());
10675
10676 if (isa<UndefValue>(V))
10677 return UndefValue::get(PTy->getElementType());
10678 else if (isa<ConstantAggregateZero>(V))
10679 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010680 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010681 return CP->getOperand(EltNo);
10682 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10683 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010684 if (!isa<ConstantInt>(III->getOperand(2)))
10685 return 0;
10686 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010687
10688 // If this is an insert to the element we are looking for, return the
10689 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010690 if (EltNo == IIElt)
10691 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010692
10693 // Otherwise, the insertelement doesn't modify the value, recurse on its
10694 // vector input.
10695 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010696 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010697 unsigned InEl = getShuffleMask(SVI)[EltNo];
10698 if (InEl < Width)
10699 return FindScalarElement(SVI->getOperand(0), InEl);
10700 else if (InEl < Width*2)
10701 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10702 else
10703 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010704 }
10705
10706 // Otherwise, we don't know.
10707 return 0;
10708}
10709
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010710Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000010711 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010712 if (isa<UndefValue>(EI.getOperand(0)))
10713 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10714
Dan Gohman07a96762007-07-16 14:29:03 +000010715 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010716 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10717 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10718
Reid Spencer9d6565a2007-02-15 02:26:10 +000010719 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000010720 // If vector val is constant with all elements the same, replace EI with
10721 // that element. When the elements are not identical, we cannot replace yet
10722 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000010723 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010724 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010725 if (C->getOperand(i) != op0) {
10726 op0 = 0;
10727 break;
10728 }
10729 if (op0)
10730 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010731 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010732
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010733 // If extracting a specified index from the vector, see if we can recursively
10734 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010735 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010736 unsigned IndexVal = IdxC->getZExtValue();
10737 unsigned VectorWidth =
10738 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10739
10740 // If this is extracting an invalid index, turn this into undef, to avoid
10741 // crashing the code below.
10742 if (IndexVal >= VectorWidth)
10743 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10744
Chris Lattner867b99f2006-10-05 06:55:50 +000010745 // This instruction only demands the single element from the input vector.
10746 // If the input vector has a single use, simplify it based on this use
10747 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010748 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010749 uint64_t UndefElts;
10750 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010751 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010752 UndefElts)) {
10753 EI.setOperand(0, V);
10754 return &EI;
10755 }
10756 }
10757
Reid Spencerb83eb642006-10-20 07:07:24 +000010758 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010759 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010760
10761 // If the this extractelement is directly using a bitcast from a vector of
10762 // the same number of elements, see if we can find the source element from
10763 // it. In this case, we will end up needing to bitcast the scalars.
10764 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10765 if (const VectorType *VT =
10766 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10767 if (VT->getNumElements() == VectorWidth)
10768 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10769 return new BitCastInst(Elt, EI.getType());
10770 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010771 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010772
Chris Lattner73fa49d2006-05-25 22:53:38 +000010773 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010774 if (I->hasOneUse()) {
10775 // Push extractelement into predecessor operation if legal and
10776 // profitable to do so
10777 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010778 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10779 if (CheapToScalarize(BO, isConstantElt)) {
10780 ExtractElementInst *newEI0 =
10781 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10782 EI.getName()+".lhs");
10783 ExtractElementInst *newEI1 =
10784 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10785 EI.getName()+".rhs");
10786 InsertNewInstBefore(newEI0, EI);
10787 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010788 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000010789 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010790 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010791 unsigned AS =
10792 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010793 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10794 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010795 GetElementPtrInst *GEP =
10796 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010797 InsertNewInstBefore(GEP, EI);
10798 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010799 }
10800 }
10801 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10802 // Extracting the inserted element?
10803 if (IE->getOperand(2) == EI.getOperand(1))
10804 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10805 // If the inserted and extracted elements are constants, they must not
10806 // be the same value, extract from the pre-inserted value instead.
10807 if (isa<Constant>(IE->getOperand(2)) &&
10808 isa<Constant>(EI.getOperand(1))) {
10809 AddUsesToWorkList(EI);
10810 EI.setOperand(0, IE->getOperand(0));
10811 return &EI;
10812 }
10813 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10814 // If this is extracting an element from a shufflevector, figure out where
10815 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010816 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10817 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010818 Value *Src;
10819 if (SrcIdx < SVI->getType()->getNumElements())
10820 Src = SVI->getOperand(0);
10821 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10822 SrcIdx -= SVI->getType()->getNumElements();
10823 Src = SVI->getOperand(1);
10824 } else {
10825 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010826 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010827 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010828 }
10829 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010830 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010831 return 0;
10832}
10833
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010834/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10835/// elements from either LHS or RHS, return the shuffle mask and true.
10836/// Otherwise, return false.
10837static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10838 std::vector<Constant*> &Mask) {
10839 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10840 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010841 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010842
10843 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010844 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010845 return true;
10846 } else if (V == LHS) {
10847 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010848 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010849 return true;
10850 } else if (V == RHS) {
10851 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010852 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010853 return true;
10854 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10855 // If this is an insert of an extract from some other vector, include it.
10856 Value *VecOp = IEI->getOperand(0);
10857 Value *ScalarOp = IEI->getOperand(1);
10858 Value *IdxOp = IEI->getOperand(2);
10859
Chris Lattnerd929f062006-04-27 21:14:21 +000010860 if (!isa<ConstantInt>(IdxOp))
10861 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010862 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010863
10864 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10865 // Okay, we can handle this if the vector we are insertinting into is
10866 // transitively ok.
10867 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10868 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010869 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010870 return true;
10871 }
10872 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10873 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010874 EI->getOperand(0)->getType() == V->getType()) {
10875 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010876 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010877
10878 // This must be extracting from either LHS or RHS.
10879 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10880 // Okay, we can handle this if the vector we are insertinting into is
10881 // transitively ok.
10882 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10883 // If so, update the mask to reflect the inserted value.
10884 if (EI->getOperand(0) == LHS) {
10885 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010886 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010887 } else {
10888 assert(EI->getOperand(0) == RHS);
10889 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010890 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010891
10892 }
10893 return true;
10894 }
10895 }
10896 }
10897 }
10898 }
10899 // TODO: Handle shufflevector here!
10900
10901 return false;
10902}
10903
10904/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10905/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10906/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010907static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010908 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010909 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010910 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010911 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010912 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010913
10914 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010915 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010916 return V;
10917 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010918 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010919 return V;
10920 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10921 // If this is an insert of an extract from some other vector, include it.
10922 Value *VecOp = IEI->getOperand(0);
10923 Value *ScalarOp = IEI->getOperand(1);
10924 Value *IdxOp = IEI->getOperand(2);
10925
10926 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10927 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10928 EI->getOperand(0)->getType() == V->getType()) {
10929 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010930 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10931 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010932
10933 // Either the extracted from or inserted into vector must be RHSVec,
10934 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010935 if (EI->getOperand(0) == RHS || RHS == 0) {
10936 RHS = EI->getOperand(0);
10937 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010938 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010939 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010940 return V;
10941 }
10942
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010943 if (VecOp == RHS) {
10944 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010945 // Everything but the extracted element is replaced with the RHS.
10946 for (unsigned i = 0; i != NumElts; ++i) {
10947 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010948 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010949 }
10950 return V;
10951 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010952
10953 // If this insertelement is a chain that comes from exactly these two
10954 // vectors, return the vector and the effective shuffle.
10955 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10956 return EI->getOperand(0);
10957
Chris Lattnerefb47352006-04-15 01:39:45 +000010958 }
10959 }
10960 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010961 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010962
10963 // Otherwise, can't do anything fancy. Return an identity vector.
10964 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010965 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010966 return V;
10967}
10968
10969Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10970 Value *VecOp = IE.getOperand(0);
10971 Value *ScalarOp = IE.getOperand(1);
10972 Value *IdxOp = IE.getOperand(2);
10973
Chris Lattner599ded12007-04-09 01:11:16 +000010974 // Inserting an undef or into an undefined place, remove this.
10975 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10976 ReplaceInstUsesWith(IE, VecOp);
10977
Chris Lattnerefb47352006-04-15 01:39:45 +000010978 // If the inserted element was extracted from some other vector, and if the
10979 // indexes are constant, try to turn this into a shufflevector operation.
10980 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10981 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10982 EI->getOperand(0)->getType() == IE.getType()) {
10983 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010984 unsigned ExtractedIdx =
10985 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010986 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010987
10988 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10989 return ReplaceInstUsesWith(IE, VecOp);
10990
10991 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10992 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10993
10994 // If we are extracting a value from a vector, then inserting it right
10995 // back into the same place, just use the input vector.
10996 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10997 return ReplaceInstUsesWith(IE, VecOp);
10998
10999 // We could theoretically do this for ANY input. However, doing so could
11000 // turn chains of insertelement instructions into a chain of shufflevector
11001 // instructions, and right now we do not merge shufflevectors. As such,
11002 // only do this in a situation where it is clear that there is benefit.
11003 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11004 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11005 // the values of VecOp, except then one read from EIOp0.
11006 // Build a new shuffle mask.
11007 std::vector<Constant*> Mask;
11008 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011009 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011010 else {
11011 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011012 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011013 NumVectorElts));
11014 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011015 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011016 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011017 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011018 }
11019
11020 // If this insertelement isn't used by some other insertelement, turn it
11021 // (and any insertelements it points to), into one big shuffle.
11022 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11023 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011024 Value *RHS = 0;
11025 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11026 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11027 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011028 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011029 }
11030 }
11031 }
11032
11033 return 0;
11034}
11035
11036
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011037Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11038 Value *LHS = SVI.getOperand(0);
11039 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011040 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011041
11042 bool MadeChange = false;
11043
Chris Lattner867b99f2006-10-05 06:55:50 +000011044 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011045 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011046 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11047
Chris Lattnere4929dd2007-01-05 07:36:08 +000011048 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011049 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011050 if (isa<UndefValue>(SVI.getOperand(1))) {
11051 // Scan to see if there are any references to the RHS. If so, replace them
11052 // with undef element refs and set MadeChange to true.
11053 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11054 if (Mask[i] >= e && Mask[i] != 2*e) {
11055 Mask[i] = 2*e;
11056 MadeChange = true;
11057 }
11058 }
11059
11060 if (MadeChange) {
11061 // Remap any references to RHS to use LHS.
11062 std::vector<Constant*> Elts;
11063 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11064 if (Mask[i] == 2*e)
11065 Elts.push_back(UndefValue::get(Type::Int32Ty));
11066 else
11067 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11068 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011069 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011070 }
11071 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011072
Chris Lattner863bcff2006-05-25 23:48:38 +000011073 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11074 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11075 if (LHS == RHS || isa<UndefValue>(LHS)) {
11076 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011077 // shuffle(undef,undef,mask) -> undef.
11078 return ReplaceInstUsesWith(SVI, LHS);
11079 }
11080
Chris Lattner863bcff2006-05-25 23:48:38 +000011081 // Remap any references to RHS to use LHS.
11082 std::vector<Constant*> Elts;
11083 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011084 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011085 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011086 else {
11087 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11088 (Mask[i] < e && isa<UndefValue>(LHS)))
11089 Mask[i] = 2*e; // Turn into undef.
11090 else
11091 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011092 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011093 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011094 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011095 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011096 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011097 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011098 LHS = SVI.getOperand(0);
11099 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011100 MadeChange = true;
11101 }
11102
Chris Lattner7b2e27922006-05-26 00:29:06 +000011103 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011104 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011105
Chris Lattner863bcff2006-05-25 23:48:38 +000011106 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11107 if (Mask[i] >= e*2) continue; // Ignore undef values.
11108 // Is this an identity shuffle of the LHS value?
11109 isLHSID &= (Mask[i] == i);
11110
11111 // Is this an identity shuffle of the RHS value?
11112 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011113 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011114
Chris Lattner863bcff2006-05-25 23:48:38 +000011115 // Eliminate identity shuffles.
11116 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11117 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011118
Chris Lattner7b2e27922006-05-26 00:29:06 +000011119 // If the LHS is a shufflevector itself, see if we can combine it with this
11120 // one without producing an unusual shuffle. Here we are really conservative:
11121 // we are absolutely afraid of producing a shuffle mask not in the input
11122 // program, because the code gen may not be smart enough to turn a merged
11123 // shuffle into two specific shuffles: it may produce worse code. As such,
11124 // we only merge two shuffles if the result is one of the two input shuffle
11125 // masks. In this case, merging the shuffles just removes one instruction,
11126 // which we know is safe. This is good for things like turning:
11127 // (splat(splat)) -> splat.
11128 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11129 if (isa<UndefValue>(RHS)) {
11130 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11131
11132 std::vector<unsigned> NewMask;
11133 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11134 if (Mask[i] >= 2*e)
11135 NewMask.push_back(2*e);
11136 else
11137 NewMask.push_back(LHSMask[Mask[i]]);
11138
11139 // If the result mask is equal to the src shuffle or this shuffle mask, do
11140 // the replacement.
11141 if (NewMask == LHSMask || NewMask == Mask) {
11142 std::vector<Constant*> Elts;
11143 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11144 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011145 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011146 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011147 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011148 }
11149 }
11150 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11151 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011152 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011153 }
11154 }
11155 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011156
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011157 return MadeChange ? &SVI : 0;
11158}
11159
11160
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011161
Chris Lattnerea1c4542004-12-08 23:43:58 +000011162
11163/// TryToSinkInstruction - Try to move the specified instruction from its
11164/// current block into the beginning of DestBlock, which can only happen if it's
11165/// safe to move the instruction past all of the instructions between it and the
11166/// end of its block.
11167static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11168 assert(I->hasOneUse() && "Invariants didn't hold!");
11169
Chris Lattner108e9022005-10-27 17:13:11 +000011170 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011171 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11172 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011173
Chris Lattnerea1c4542004-12-08 23:43:58 +000011174 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011175 if (isa<AllocaInst>(I) && I->getParent() ==
11176 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011177 return false;
11178
Chris Lattner96a52a62004-12-09 07:14:34 +000011179 // We can only sink load instructions if there is nothing between the load and
11180 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011181 if (I->mayReadFromMemory()) {
11182 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011183 Scan != E; ++Scan)
11184 if (Scan->mayWriteToMemory())
11185 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011186 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011187
Dan Gohman02dea8b2008-05-23 21:05:58 +000011188 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011189
Chris Lattner4bc5f802005-08-08 19:11:57 +000011190 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011191 ++NumSunkInst;
11192 return true;
11193}
11194
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011195
11196/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11197/// all reachable code to the worklist.
11198///
11199/// This has a couple of tricks to make the code faster and more powerful. In
11200/// particular, we constant fold and DCE instructions as we go, to avoid adding
11201/// them to the worklist (this significantly speeds up instcombine on code where
11202/// many instructions are dead or constant). Additionally, if we find a branch
11203/// whose condition is a known constant, we only visit the reachable successors.
11204///
11205static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011206 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011207 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011208 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011209 std::vector<BasicBlock*> Worklist;
11210 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011211
Chris Lattner2c7718a2007-03-23 19:17:18 +000011212 while (!Worklist.empty()) {
11213 BB = Worklist.back();
11214 Worklist.pop_back();
11215
11216 // We have now visited this block! If we've already been here, ignore it.
11217 if (!Visited.insert(BB)) continue;
11218
11219 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11220 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011221
Chris Lattner2c7718a2007-03-23 19:17:18 +000011222 // DCE instruction if trivially dead.
11223 if (isInstructionTriviallyDead(Inst)) {
11224 ++NumDeadInst;
11225 DOUT << "IC: DCE: " << *Inst;
11226 Inst->eraseFromParent();
11227 continue;
11228 }
11229
11230 // ConstantProp instruction if trivially constant.
11231 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11232 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11233 Inst->replaceAllUsesWith(C);
11234 ++NumConstProp;
11235 Inst->eraseFromParent();
11236 continue;
11237 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011238
Chris Lattner2c7718a2007-03-23 19:17:18 +000011239 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011240 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011241
11242 // Recursively visit successors. If this is a branch or switch on a
11243 // constant, only visit the reachable successor.
11244 TerminatorInst *TI = BB->getTerminator();
11245 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11246 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11247 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011248 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011249 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011250 continue;
11251 }
11252 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11253 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11254 // See if this is an explicit destination.
11255 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11256 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011257 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011258 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011259 continue;
11260 }
11261
11262 // Otherwise it is the default destination.
11263 Worklist.push_back(SI->getSuccessor(0));
11264 continue;
11265 }
11266 }
11267
11268 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11269 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011270 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011271}
11272
Chris Lattnerec9c3582007-03-03 02:04:50 +000011273bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011274 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011275 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011276
11277 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11278 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011279
Chris Lattnerb3d59702005-07-07 20:40:38 +000011280 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011281 // Do a depth-first traversal of the function, populate the worklist with
11282 // the reachable instructions. Ignore blocks that are not reachable. Keep
11283 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011284 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011285 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011286
Chris Lattnerb3d59702005-07-07 20:40:38 +000011287 // Do a quick scan over the function. If we find any blocks that are
11288 // unreachable, remove any instructions inside of them. This prevents
11289 // the instcombine code from having to deal with some bad special cases.
11290 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11291 if (!Visited.count(BB)) {
11292 Instruction *Term = BB->getTerminator();
11293 while (Term != BB->begin()) { // Remove instrs bottom-up
11294 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011295
Bill Wendlingb7427032006-11-26 09:46:52 +000011296 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011297 ++NumDeadInst;
11298
11299 if (!I->use_empty())
11300 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11301 I->eraseFromParent();
11302 }
11303 }
11304 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011305
Chris Lattnerdbab3862007-03-02 21:28:56 +000011306 while (!Worklist.empty()) {
11307 Instruction *I = RemoveOneFromWorkList();
11308 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011309
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011310 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011311 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011312 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011313 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011314 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011315 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011316
Bill Wendlingb7427032006-11-26 09:46:52 +000011317 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011318
11319 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011320 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011321 continue;
11322 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011323
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011324 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011325 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011326 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011327
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011328 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011329 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011330 ReplaceInstUsesWith(*I, C);
11331
Chris Lattner62b14df2002-09-02 04:59:56 +000011332 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011333 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011334 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011335 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011336 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011337
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000011338 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11339 // See if we can constant fold its operands.
11340 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11341 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11342 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11343 i->set(NewC);
11344 }
11345 }
11346 }
11347
Chris Lattnerea1c4542004-12-08 23:43:58 +000011348 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011349 // FIXME: Remove GetResultInst test when first class support for aggregates
11350 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011351 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011352 BasicBlock *BB = I->getParent();
11353 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11354 if (UserParent != BB) {
11355 bool UserIsSuccessor = false;
11356 // See if the user is one of our successors.
11357 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11358 if (*SI == UserParent) {
11359 UserIsSuccessor = true;
11360 break;
11361 }
11362
11363 // If the user is one of our immediate successors, and if that successor
11364 // only has us as a predecessors (we'd have to split the critical edge
11365 // otherwise), we can keep going.
11366 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11367 next(pred_begin(UserParent)) == pred_end(UserParent))
11368 // Okay, the CFG is simple enough, try to sink this instruction.
11369 Changed |= TryToSinkInstruction(I, UserParent);
11370 }
11371 }
11372
Chris Lattner8a2a3112001-12-14 16:52:21 +000011373 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011374#ifndef NDEBUG
11375 std::string OrigI;
11376#endif
11377 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011378 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011379 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011380 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011381 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011382 DOUT << "IC: Old = " << *I
11383 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011384
Chris Lattnerf523d062004-06-09 05:08:07 +000011385 // Everything uses the new instruction now.
11386 I->replaceAllUsesWith(Result);
11387
11388 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011389 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011390 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011391
Chris Lattner6934a042007-02-11 01:23:03 +000011392 // Move the name to the new instruction first.
11393 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011394
11395 // Insert the new instruction into the basic block...
11396 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011397 BasicBlock::iterator InsertPos = I;
11398
11399 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11400 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11401 ++InsertPos;
11402
11403 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011404
Chris Lattner00d51312004-05-01 23:27:23 +000011405 // Make sure that we reprocess all operands now that we reduced their
11406 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011407 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011408
Chris Lattnerf523d062004-06-09 05:08:07 +000011409 // Instructions can end up on the worklist more than once. Make sure
11410 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011411 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011412
11413 // Erase the old instruction.
11414 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011415 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011416#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011417 DOUT << "IC: Mod = " << OrigI
11418 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011419#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011420
Chris Lattner90ac28c2002-08-02 19:29:35 +000011421 // If the instruction was modified, it's possible that it is now dead.
11422 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011423 if (isInstructionTriviallyDead(I)) {
11424 // Make sure we process all operands now that we are reducing their
11425 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011426 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011427
Chris Lattner00d51312004-05-01 23:27:23 +000011428 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011429 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011430 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011431 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011432 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011433 AddToWorkList(I);
11434 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011435 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011436 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011437 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011438 }
11439 }
11440
Chris Lattnerec9c3582007-03-03 02:04:50 +000011441 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011442
11443 // Do an explicit clear, this shrinks the map if needed.
11444 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011445 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011446}
11447
Chris Lattnerec9c3582007-03-03 02:04:50 +000011448
11449bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011450 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11451
Chris Lattnerec9c3582007-03-03 02:04:50 +000011452 bool EverMadeChange = false;
11453
11454 // Iterate while there is work to do.
11455 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011456 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011457 EverMadeChange = true;
11458 return EverMadeChange;
11459}
11460
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011461FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011462 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011463}
Brian Gaeked0fde302003-11-11 22:41:34 +000011464